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 9fdcf4c752..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', '3.12' ] + python-version: [ '3.8', '3.9', '3.10', '3.11', '3.12', '3.13' ] steps: - name: Checkout twilio-python uses: actions/checkout@v3 @@ -47,6 +47,7 @@ jobs: TWILIO_FROM_NUMBER: ${{ secrets.TWILIO_FROM_NUMBER }} TWILIO_TO_NUMBER: ${{ secrets.TWILIO_TO_NUMBER }} TWILIO_AUTH_TOKEN: ${{ secrets.TWILIO_AUTH_TOKEN }} + ASSISTANT_ID: ${{ secrets.ASSISTANT_ID }} run: make cluster-test - name: Verify docs generation diff --git a/CHANGES.md b/CHANGES.md index a9e6811010..5ac12d5bb4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,6 +3,939 @@ 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** 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/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 a29abc4d1e..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 -requests>=2.31.0 +requests>=2.32.2 PyJWT>=2.0.0, <3.0.0 -aiohttp>=3.9.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 index 8fee9aa182..09672cd205 100644 --- a/setup.py +++ b/setup.py @@ -13,7 +13,7 @@ setup( name="twilio", - version="9.2.3", + version="9.10.9", description="Twilio API client and TwiML generator", author="Twilio", help_center="https://www.twilio.com/help/contact", @@ -39,6 +39,8 @@ "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", "Programming Language :: Python :: Implementation :: CPython", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Communications :: Telephony", diff --git a/tests/cluster/test_cluster.py b/tests/cluster/test_cluster.py index 556fa8da75..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, @@ -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/holodeck.py b/tests/holodeck.py index 8f71514314..81db67683b 100644 --- a/tests/holodeck.py +++ b/tests/holodeck.py @@ -1,5 +1,5 @@ from twilio.base.exceptions import TwilioRestException -from twilio.http import HttpClient +from twilio.http import HttpClient, AsyncHttpClient from twilio.http.request import Request import platform from twilio import __version__ @@ -15,6 +15,7 @@ class Holodeck(HttpClient): def __init__(self): self._holograms = [] self._requests = [] + self.is_async = False def mock(self, response, request=None): request = request or Request() @@ -87,3 +88,86 @@ def request( message += "No Holograms loaded" raise TwilioRestException(404, url, message, method=method) + + +class AsyncHolodeck(AsyncHttpClient): + """Async version of Holodeck for async testing""" + + def __init__(self): + # Don't call super().__init__() to avoid logger requirement + self._holograms = [] + self._requests = [] + self.is_async = True + + def mock(self, response, request=None): + request = request or Request() + self._holograms.append(Hologram(request, response)) + + @property + def requests(self): + return self._requests + + def add_standard_headers(self, request): + standard_headers = { + "User-Agent": "twilio-python/{} ({} {}) Python/{}".format( + __version__, + platform.system(), + platform.machine(), + platform.python_version(), + ), + "X-Twilio-Client": "python-{}".format(__version__), + "Accept": "application/json", + "Accept-Charset": "utf-8", + } + + if request.method == "POST" and "Content-Type" not in standard_headers: + standard_headers["Content-Type"] = "application/x-www-form-urlencoded" + + standard_headers.update(request.headers) + request.headers = standard_headers + return request + + def assert_has_request(self, request): + for req in self.requests: + if req == request or req == self.add_standard_headers(request): + return + + message = "\nHolodeck never received a request matching: \n + {}\n".format( + request + ) + if self._requests: + message += "Requests received:\n" + message += "\n".join(" * {}".format(r) for r in self.requests) + else: + message += "No Requests received" + + raise AssertionError(message) + + async def request( + self, + method, + url, + params=None, + data=None, + headers=None, + auth=None, + timeout=None, + allow_redirects=False, + ): + """Async request method""" + request = Request(method, url, auth, params, data, headers) + + self._requests.append(request) + + for hologram in self._holograms: + if hologram.request == request: + return hologram.response + + message = "\nHolodeck has no hologram for: {}\n".format(request) + if self._holograms: + message += "Holograms loaded:\n" + message += "\n".join(" - {}".format(h.request) for h in self._holograms) + else: + message += "No Holograms loaded" + + raise TwilioRestException(404, url, message, method=method) diff --git a/tests/unit/base/test_token_pagination.py b/tests/unit/base/test_token_pagination.py new file mode 100644 index 0000000000..2de67831cd --- /dev/null +++ b/tests/unit/base/test_token_pagination.py @@ -0,0 +1,749 @@ +import unittest +from unittest.mock import Mock +from tests import IntegrationTestCase +from tests.holodeck import Request +from twilio.base.exceptions import TwilioException +from twilio.base.token_pagination import TokenPagination +from twilio.http.response import Response + + +class MockTokenPaginationPage(TokenPagination): + """Mock implementation of TokenPagination for testing""" + + def get_instance(self, payload): + return payload + + +class TokenPaginationPropertyTest(unittest.TestCase): + """Test TokenPagination property accessors""" + + def setUp(self): + self.version = Mock() + self.version.domain = Mock() + + # Mock response with token pagination format + self.payload = { + "meta": { + "key": "items", + "pageSize": 50, + "nextToken": "next_abc123", + "previousToken": "prev_xyz789", + }, + "items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}], + } + + self.response = Mock() + self.response.text = """ + { + "meta": { + "key": "items", + "pageSize": 50, + "nextToken": "next_abc123", + "previousToken": "prev_xyz789" + }, + "items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}] + } + """ + self.response.status_code = 200 + + self.solution = { + "account_sid": "ACxxxx", + } + self.page = MockTokenPaginationPage( + self.version, + self.response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + def test_key_property(self): + """Test that key property returns the correct value""" + self.assertEqual(self.page.key, "items") + + def test_page_size_property(self): + """Test that page_size property returns the correct value""" + self.assertEqual(self.page.page_size, 50) + + def test_next_token_property(self): + """Test that next_token property returns the correct value""" + self.assertEqual(self.page.next_token, "next_abc123") + + def test_previous_token_property(self): + """Test that previous_token property returns the correct value""" + self.assertEqual(self.page.previous_token, "prev_xyz789") + + def test_properties_without_meta(self): + """Test that properties return None when meta is missing""" + response = Mock() + response.text = '{"items": []}' + response.status_code = 200 + + page = MockTokenPaginationPage( + self.version, response, "/Accounts/ACxxxx/Resources.json", {}, self.solution + ) + + self.assertIsNone(page.key) + self.assertIsNone(page.page_size) + self.assertIsNone(page.next_token) + self.assertIsNone(page.previous_token) + + def test_properties_with_partial_meta(self): + """Test that properties return None when specific keys are missing""" + response = Mock() + response.text = '{"meta": {"key": "items"}, "items": []}' + response.status_code = 200 + + page = MockTokenPaginationPage( + self.version, response, "/Accounts/ACxxxx/Resources.json", {}, self.solution + ) + + self.assertEqual(page.key, "items") + self.assertIsNone(page.page_size) + self.assertIsNone(page.next_token) + self.assertIsNone(page.previous_token) + + +class TokenPaginationNavigationTest(IntegrationTestCase): + """Test TokenPagination next_page and previous_page methods""" + + def setUp(self): + super(TokenPaginationNavigationTest, self).setUp() + + # Mock first page response + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={}, + ), + ) + + # Mock second page response (next page) + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page3", + "previousToken": "token_prev1" + }, + "items": [{"id": 3, "name": "Item 3"}, {"id": 4, "name": "Item 4"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={"pageToken": "token_page2"}, + ), + ) + + # Mock third page response (has no next) + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": null, + "previousToken": "token_prev2" + }, + "items": [{"id": 5, "name": "Item 5"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={"pageToken": "token_page3"}, + ), + ) + + # Mock previous page response (going back to page 1) + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={"pageToken": "token_prev1"}, + ), + ) + + # Mock going back from page 3 to page 2 + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page3", + "previousToken": "token_prev1" + }, + "items": [{"id": 3, "name": "Item 3"}, {"id": 4, "name": "Item 4"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Resources.json", + params={"pageToken": "token_prev2"}, + ), + ) + + self.version = self.client.api.v2010 + self.response = self.version.page( + method="GET", uri="/Accounts/ACaaaa/Resources.json" + ) + + self.solution = { + "account_sid": "ACaaaa", + } + + self.page = MockTokenPaginationPage( + self.version, + self.response, + "/Accounts/ACaaaa/Resources.json", + {}, + self.solution, + ) + + def test_next_page(self): + """Test that next_page() navigates to the next page using token""" + self.assertIsNotNone(self.page.next_token) + self.assertEqual(self.page.next_token, "token_page2") + + next_page = self.page.next_page() + + self.assertIsNotNone(next_page) + self.assertIsInstance(next_page, MockTokenPaginationPage) + # Verify we got the next page's data + self.assertEqual(next_page.next_token, "token_page3") + self.assertEqual(next_page.previous_token, "token_prev1") + + def test_next_page_none_when_no_token(self): + """Test that next_page() returns None when there's no next token""" + # Navigate to the last page + next_page = self.page.next_page() + last_page = next_page.next_page() + + # Last page should have no next token + self.assertIsNone(last_page.next_token) + + # next_page() should return None + result = last_page.next_page() + self.assertIsNone(result) + + def test_previous_page(self): + """Test that previous_page() navigates to the previous page using token""" + # Navigate to second page first + next_page = self.page.next_page() + self.assertIsNotNone(next_page.previous_token) + self.assertEqual(next_page.previous_token, "token_prev1") + + # Go back to previous page + prev_page = next_page.previous_page() + + self.assertIsNotNone(prev_page) + self.assertIsInstance(prev_page, MockTokenPaginationPage) + # Verify we got the first page's data + self.assertIsNone(prev_page.previous_token) + self.assertEqual(prev_page.next_token, "token_page2") + + def test_previous_page_none_when_no_token(self): + """Test that previous_page() returns None when there's no previous token""" + # First page should have no previous token + self.assertIsNone(self.page.previous_token) + + # previous_page() should return None + result = self.page.previous_page() + self.assertIsNone(result) + + def test_navigation_chain(self): + """Test navigating through multiple pages forward and backward""" + # Page 1 -> Page 2 + page2 = self.page.next_page() + self.assertEqual(page2.previous_token, "token_prev1") + + # Page 2 -> Page 3 + page3 = page2.next_page() + self.assertIsNone(page3.next_token) + self.assertEqual(page3.previous_token, "token_prev2") + + # Page 3 -> Page 2 (backward) + back_to_page2 = page3.previous_page() + self.assertIsNotNone(back_to_page2) + + +class TokenPaginationErrorTest(unittest.TestCase): + """Test TokenPagination error handling""" + + def test_next_page_without_uri_in_solution(self): + """Test that next_page() raises error when URI is missing""" + version = Mock() + response = Mock() + response.text = """ + { + "meta": { + "key": "items", + "pageSize": 50, + "nextToken": "abc123" + }, + "items": [] + } + """ + response.status_code = 200 + + # Solution without URI + solution = {"account_sid": "ACxxxx"} + + # Pass empty string as URI to test the error case + page = MockTokenPaginationPage(version, response, "", {}, solution) + + with self.assertRaises(TwilioException) as context: + page.next_page() + + self.assertIn("URI must be provided", str(context.exception)) + + +class TokenPaginationStreamTest(IntegrationTestCase): + """Test streaming with TokenPagination""" + + def setUp(self): + super(TokenPaginationStreamTest, self).setUp() + + # Mock page 1 + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "records", + "pageSize": 2, + "nextToken": "token_2" + }, + "records": [{"id": 1}, {"id": 2}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Records.json", + params={}, + ), + ) + + # Mock page 2 + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "records", + "pageSize": 2, + "nextToken": "token_3", + "previousToken": "token_2" + }, + "records": [{"id": 3}, {"id": 4}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Records.json", + params={"pageToken": "token_2"}, + ), + ) + + # Mock page 3 (final) + self.holodeck.mock( + Response( + 200, + """ + { + "meta": { + "key": "records", + "pageSize": 2, + "nextToken": null, + "previousToken": "token_3" + }, + "records": [{"id": 5}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/ACaaaa/Records.json", + params={"pageToken": "token_3"}, + ), + ) + + self.version = self.client.api.v2010 + self.response = self.version.page( + method="GET", uri="/Accounts/ACaaaa/Records.json" + ) + + self.solution = { + "account_sid": "ACaaaa", + } + + self.page = MockTokenPaginationPage( + self.version, + self.response, + "/Accounts/ACaaaa/Records.json", + {}, + self.solution, + ) + + def test_stream_all_records(self): + """Test streaming through all pages""" + records = list(self.version.stream(self.page)) + + self.assertEqual(len(records), 5) + self.assertEqual(records[0]["id"], 1) + self.assertEqual(records[4]["id"], 5) + + def test_stream_with_limit(self): + """Test streaming with a limit""" + records = list(self.version.stream(self.page, limit=3)) + + self.assertEqual(len(records), 3) + self.assertEqual(records[0]["id"], 1) + self.assertEqual(records[2]["id"], 3) + + def test_stream_with_page_limit(self): + """Test streaming with page limit""" + records = list(self.version.stream(self.page, page_limit=1)) + + # Only first page (2 records) + self.assertEqual(len(records), 2) + + +class TokenPaginationInternalMethodTest(unittest.TestCase): + """Test TokenPagination internal methods""" + + def setUp(self): + self.version = Mock() + self.version.domain = Mock() + self.version.domain.twilio = Mock() + self.version.domain.absolute_url = Mock( + side_effect=lambda uri: f"https://api.twilio.com{uri}" + ) + + # Mock first page response + self.first_response = Mock() + self.first_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1}, {"id": 2}] + } + """ + self.first_response.status_code = 200 + + # Mock next page response + self.next_response = Mock() + self.next_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": null, + "previousToken": "token_prev" + }, + "items": [{"id": 3}, {"id": 4}] + } + """ + self.next_response.status_code = 200 + + self.solution = {"account_sid": "ACxxxx"} + self.page = MockTokenPaginationPage( + self.version, + self.first_response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + def test_get_page_with_valid_token(self): + """Test _get_page() with a valid token""" + self.version.page = Mock(return_value=self.next_response) + + result = self.page._get_page("token_page2") + + self.assertIsNotNone(result) + self.assertIsInstance(result, MockTokenPaginationPage) + self.version.page.assert_called_once_with( + method="GET", + uri="/Accounts/ACxxxx/Resources.json", + params={"pageToken": "token_page2"}, + ) + + def test_get_page_with_none_token(self): + """Test _get_page() with None token returns None""" + result = self.page._get_page(None) + self.assertIsNone(result) + + def test_get_page_without_uri(self): + """Test _get_page() raises error when URI is missing""" + page = MockTokenPaginationPage( + self.version, self.first_response, "", {}, self.solution + ) + + with self.assertRaises(TwilioException) as context: + page._get_page("some_token") + + self.assertIn("URI must be provided", str(context.exception)) + + def test_repr(self): + """Test __repr__ method returns correct string""" + self.assertEqual(repr(self.page), "") + + def test_params_preserved_across_pagination(self): + """Test that initial query params are preserved when fetching next page""" + # Create a page with initial query parameters + initial_params = {"status": "active", "limit": 50} + page_with_params = MockTokenPaginationPage( + self.version, + self.first_response, + "/Accounts/ACxxxx/Resources.json", + initial_params, + self.solution, + ) + + self.version.page = Mock(return_value=self.next_response) + + # Fetch the next page + result = page_with_params._get_page("token_page2") + + # Verify that the initial params are preserved and pageToken is added + self.assertIsNotNone(result) + self.version.page.assert_called_once_with( + method="GET", + uri="/Accounts/ACxxxx/Resources.json", + params={"status": "active", "limit": 50, "pageToken": "token_page2"}, + ) + + +class TokenPaginationAsyncTest(unittest.IsolatedAsyncioTestCase): + """Test TokenPagination async methods""" + + def setUp(self): + self.version = Mock() + self.version.domain = Mock() + self.version.domain.twilio = Mock() + self.version.domain.absolute_url = Mock( + side_effect=lambda uri: f"https://api.twilio.com{uri}" + ) + + # Mock first page response + self.first_response = Mock() + self.first_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1}, {"id": 2}] + } + """ + self.first_response.status_code = 200 + + # Mock next page response + self.next_response = Mock() + self.next_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page3", + "previousToken": "token_prev" + }, + "items": [{"id": 3}, {"id": 4}] + } + """ + self.next_response.status_code = 200 + + # Mock previous page response + self.prev_response = Mock() + self.prev_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": "token_page2", + "previousToken": null + }, + "items": [{"id": 1}, {"id": 2}] + } + """ + self.prev_response.status_code = 200 + + self.solution = {"account_sid": "ACxxxx"} + + # Page with next token + self.page = MockTokenPaginationPage( + self.version, + self.first_response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + # Page with previous token (page 2) + self.page_with_prev = MockTokenPaginationPage( + self.version, + self.next_response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + async def test_get_page_async_with_valid_token(self): + """Test _get_page_async() with a valid token""" + self.version.page = Mock(return_value=self.next_response) + + result = await self.page._get_page_async("token_page2") + + self.assertIsNotNone(result) + self.assertIsInstance(result, MockTokenPaginationPage) + self.version.page.assert_called_once_with( + method="GET", + uri="/Accounts/ACxxxx/Resources.json", + params={"pageToken": "token_page2"}, + ) + + async def test_get_page_async_with_none_token(self): + """Test _get_page_async() with None token returns None""" + result = await self.page._get_page_async(None) + self.assertIsNone(result) + + async def test_get_page_async_without_uri(self): + """Test _get_page_async() raises error when URI is missing""" + page = MockTokenPaginationPage( + self.version, self.first_response, "", {}, self.solution + ) + + with self.assertRaises(TwilioException) as context: + await page._get_page_async("some_token") + + self.assertIn("URI must be provided", str(context.exception)) + + async def test_next_page_async(self): + """Test next_page_async() navigates to next page""" + self.version.page = Mock(return_value=self.next_response) + + next_page = await self.page.next_page_async() + + self.assertIsNotNone(next_page) + self.assertIsInstance(next_page, MockTokenPaginationPage) + self.assertEqual(next_page.next_token, "token_page3") + self.assertEqual(next_page.previous_token, "token_prev") + + async def test_next_page_async_none_when_no_token(self): + """Test next_page_async() returns None when there's no next token""" + # Create page with no next token + no_next_response = Mock() + no_next_response.text = """ + { + "meta": { + "key": "items", + "pageSize": 2, + "nextToken": null, + "previousToken": "token_prev" + }, + "items": [{"id": 5}] + } + """ + no_next_response.status_code = 200 + + page = MockTokenPaginationPage( + self.version, + no_next_response, + "/Accounts/ACxxxx/Resources.json", + {}, + self.solution, + ) + + result = await page.next_page_async() + self.assertIsNone(result) + + async def test_previous_page_async(self): + """Test previous_page_async() navigates to previous page""" + self.version.page = Mock(return_value=self.prev_response) + + prev_page = await self.page_with_prev.previous_page_async() + + self.assertIsNotNone(prev_page) + self.assertIsInstance(prev_page, MockTokenPaginationPage) + self.assertIsNone(prev_page.previous_token) + self.assertEqual(prev_page.next_token, "token_page2") + + async def test_previous_page_async_none_when_no_token(self): + """Test previous_page_async() returns None when there's no previous token""" + # First page has no previous token + result = await self.page.previous_page_async() + self.assertIsNone(result) + + async def test_params_preserved_across_pagination_async(self): + """Test that initial query params are preserved when fetching next page async""" + # Create a page with initial query parameters + initial_params = {"status": "active", "limit": 50} + page_with_params = MockTokenPaginationPage( + self.version, + self.first_response, + "/Accounts/ACxxxx/Resources.json", + initial_params, + self.solution, + ) + + self.version.page = Mock(return_value=self.next_response) + + # Fetch the next page + result = await page_with_params._get_page_async("token_page2") + + # Verify that the initial params are preserved and pageToken is added + self.assertIsNotNone(result) + self.version.page.assert_called_once_with( + method="GET", + uri="/Accounts/ACxxxx/Resources.json", + params={"status": "active", "limit": 50, "pageToken": "token_page2"}, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/base/test_version.py b/tests/unit/base/test_version.py index 1f1f6395eb..03c684a2ff 100644 --- a/tests/unit/base/test_version.py +++ b/tests/unit/base/test_version.py @@ -1,5 +1,15 @@ +import unittest +from unittest.mock import Mock + +import aiounittest from tests import IntegrationTestCase from tests.holodeck import Request +from twilio.base.version import Version +from twilio.base.exceptions import ( + TwilioRestException, + TwilioServiceException, + TwilioException, +) from twilio.base.page import Page from twilio.http.response import Response @@ -89,3 +99,1141 @@ def test_fetch_redirect(self): response = self.client.messaging.v1.fetch(method="GET", uri="/Deactivations") self.assertIsNotNone(response) + + def test_delete_success(self): + self.holodeck.mock( + Response(201, ""), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + result = self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + + self.assertTrue(result) + + def test_delete_not_found(self): + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM456.json", + ), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Messages/MM456.json" + ) + + self.assertIn("Unable to delete record", str(context.exception)) + + def test_delete_with_response_body(self): + """Test delete that returns JSON response body (V1 API style)""" + self.holodeck.mock( + Response( + 202, + '{"sid": "DE123", "status": "deleted", "account_sid": "AC123"}', + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result = self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + + self.assertIsInstance(result, dict) + self.assertEqual(result["sid"], "DE123") + self.assertEqual(result["status"], "deleted") + self.assertEqual(result["account_sid"], "AC123") + + def test_delete_no_content(self): + """Test traditional delete with no content (204)""" + self.holodeck.mock( + Response(204, ""), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + result = self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + + self.assertTrue(result) + self.assertIsInstance(result, bool) + + def test_delete_with_invalid_json(self): + """Test delete with response content that is not valid JSON""" + self.holodeck.mock( + Response(200, "Not valid JSON content"), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result = self.client.api.v2010.delete( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + + # Should fallback to boolean True when JSON parsing fails + self.assertTrue(result) + self.assertIsInstance(result, bool) + + +class VersionExceptionTestCase(unittest.TestCase): + """Test cases for base Version.exception() method with RFC-9457 auto-detection""" + + def test_exception_rfc9457_auto_detection(self): + """Test that base Version auto-detects RFC-9457 errors and creates TwilioServiceException""" + response = Mock(spec=Response) + response.status_code = 400 + response.text = """{ + "type": "https://www.twilio.com/docs/api/errors/20001", + "title": "Invalid parameter", + "status": 400, + "code": 20001, + "detail": "The 'PhoneNumber' parameter is required.", + "instance": "/api/v1/accounts/AC123/calls/CA456" + }""" + + exception = Version.exception( + method="POST", uri="/test", response=response, message="Test error" + ) + + self.assertIsInstance(exception, TwilioServiceException) + self.assertEqual(exception.type, "https://www.twilio.com/docs/api/errors/20001") + self.assertEqual(exception.title, "Invalid parameter") + self.assertEqual(exception.status, 400) + self.assertEqual(exception.code, 20001) + self.assertEqual(exception.detail, "The 'PhoneNumber' parameter is required.") + self.assertEqual(exception.instance, "/api/v1/accounts/AC123/calls/CA456") + self.assertEqual(exception.method, "POST") + self.assertEqual(exception.uri, "/test") + + def test_exception_legacy_format_fallback(self): + """Test that base Version falls back to TwilioRestException for legacy errors""" + response = Mock(spec=Response) + response.status_code = 400 + response.text = """{ + "message": "Invalid phone number", + "code": 21211 + }""" + + exception = Version.exception( + method="POST", uri="/test", response=response, message="Test error" + ) + + self.assertIsInstance(exception, TwilioRestException) + self.assertEqual(exception.status, 400) + self.assertEqual(exception.code, 21211) + self.assertIn("Invalid phone number", exception.msg) + + def test_exception_rfc9457_with_validation_errors_base_version(self): + """Test base Version handles RFC-9457 with validation errors array""" + response = Mock(spec=Response) + response.status_code = 422 + response.text = """{ + "type": "https://www.twilio.com/docs/api/errors/20001", + "title": "Validation failed", + "status": 422, + "code": 20001, + "detail": "Request validation failed", + "errors": [ + {"detail": "must be a positive integer", "pointer": "#/age"}, + {"detail": "must be 'green', 'red' or 'blue'", "pointer": "#/profile/color"} + ] + }""" + + exception = Version.exception( + method="POST", uri="/test", response=response, message="Validation error" + ) + + self.assertIsInstance(exception, TwilioServiceException) + self.assertEqual(exception.title, "Validation failed") + self.assertEqual(len(exception.errors), 2) + self.assertEqual(exception.errors[0]["detail"], "must be a positive integer") + self.assertEqual(exception.errors[0]["pointer"], "#/age") + + def test_exception_malformed_json_fallback(self): + """Test that base Version handles malformed JSON gracefully""" + response = Mock(spec=Response) + response.status_code = 500 + response.text = "This is not JSON" + + exception = Version.exception( + method="GET", uri="/test", response=response, message="Server error" + ) + + self.assertIsInstance(exception, TwilioRestException) + self.assertEqual(exception.status, 500) + + +class TwilioServiceExceptionTestCase(unittest.TestCase): + """Comprehensive test cases for TwilioServiceException""" + + def test_minimal_required_fields(self): + """Test TwilioServiceException with only required fields""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20003", + title="Authentication Failed", + status=401, + code=20003, + ) + + self.assertEqual(exc.type, "https://www.twilio.com/docs/api/errors/20003") + self.assertEqual(exc.title, "Authentication Failed") + self.assertEqual(exc.status, 401) + self.assertEqual(exc.code, 20003) + self.assertIsNone(exc.detail) + self.assertIsNone(exc.instance) + self.assertEqual(exc.errors, []) + self.assertEqual(exc.method, "GET") + self.assertEqual(exc.uri, "") + + def test_all_fields_populated(self): + """Test TwilioServiceException with all fields populated""" + errors = [ + {"detail": "Field is required", "pointer": "#/name"}, + {"detail": "Must be a valid email", "pointer": "#/email"}, + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Invalid Request", + status=400, + code=20001, + detail="The request could not be processed", + instance="/api/v1/accounts/AC123/messages/SM456", + errors=errors, + method="POST", + uri="/api/v1/messages", + ) + + self.assertEqual(exc.type, "https://www.twilio.com/docs/api/errors/20001") + self.assertEqual(exc.title, "Invalid Request") + self.assertEqual(exc.status, 400) + self.assertEqual(exc.code, 20001) + self.assertEqual(exc.detail, "The request could not be processed") + self.assertEqual(exc.instance, "/api/v1/accounts/AC123/messages/SM456") + self.assertEqual(len(exc.errors), 2) + self.assertEqual(exc.errors[0]["detail"], "Field is required") + self.assertEqual(exc.errors[0]["pointer"], "#/name") + self.assertEqual(exc.method, "POST") + self.assertEqual(exc.uri, "/api/v1/messages") + + def test_partial_optional_fields(self): + """Test TwilioServiceException with some optional fields""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20002", + title="Rate Limit Exceeded", + status=429, + code=20002, + detail="Too many requests", + method="POST", + uri="/api/v1/calls", + ) + + self.assertEqual(exc.detail, "Too many requests") + self.assertIsNone(exc.instance) + self.assertEqual(exc.errors, []) + self.assertEqual(exc.method, "POST") + self.assertEqual(exc.uri, "/api/v1/calls") + + def test_empty_errors_array(self): + """Test TwilioServiceException with explicitly empty errors array""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Bad Request", + status=400, + code=20001, + errors=[], + ) + + self.assertEqual(exc.errors, []) + + def test_none_errors_becomes_empty_list(self): + """Test that None errors parameter becomes empty list""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Bad Request", + status=400, + code=20001, + errors=None, + ) + + self.assertEqual(exc.errors, []) + self.assertIsInstance(exc.errors, list) + + def test_different_http_methods(self): + """Test TwilioServiceException with different HTTP methods""" + methods = ["GET", "POST", "PUT", "PATCH", "DELETE"] + + for method in methods: + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Error", + status=400, + code=20001, + method=method, + ) + self.assertEqual(exc.method, method) + + def test_different_status_codes(self): + """Test TwilioServiceException with various HTTP status codes""" + status_codes = [400, 401, 403, 404, 422, 429, 500, 502, 503] + + for status_code in status_codes: + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Error", + status=status_code, + code=20001, + ) + self.assertEqual(exc.status, status_code) + + def test_string_representation_non_tty(self): + """Test __str__ method for non-TTY output (plain text)""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Invalid Parameter", + status=400, + code=20001, + detail="The PhoneNumber parameter is required", + ) + + # Mock sys.stderr to simulate non-TTY + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=False) + + result = str(exc) + + self.assertIn("HTTP 400 error", result) + self.assertIn("Invalid Parameter", result) + self.assertIn("The PhoneNumber parameter is required", result) + finally: + sys.stderr = original_stderr + + def test_string_representation_non_tty_with_validation_errors(self): + """Test __str__ method for non-TTY with validation errors""" + errors = [ + {"detail": "must be positive", "pointer": "#/age"}, + {"detail": "must be valid email", "pointer": "#/email"}, + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Validation Failed", + status=422, + code=20001, + detail="Request validation failed", + errors=errors, + ) + + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=False) + + result = str(exc) + + self.assertIn("HTTP 422 error", result) + self.assertIn("Validation Failed", result) + self.assertIn("Request validation failed", result) + self.assertIn("Validation errors", result) + self.assertIn("#/age", result) + self.assertIn("must be positive", result) + finally: + sys.stderr = original_stderr + + def test_string_representation_tty(self): + """Test __str__ method for TTY output (colored)""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Invalid Parameter", + status=400, + code=20001, + detail="The PhoneNumber parameter is required", + instance="/api/v1/accounts/AC123/calls/CA456", + method="POST", + uri="/api/v1/calls", + ) + + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=True) + + result = str(exc) + + # Check for ANSI escape codes (color formatting) + self.assertIn("\033[", result) + # Check for content + self.assertIn("HTTP Error", result) + self.assertIn("POST /api/v1/calls", result) + self.assertIn("Invalid Parameter", result) + self.assertIn("The PhoneNumber parameter is required", result) + self.assertIn("400", result) + self.assertIn("20001", result) + self.assertIn("https://www.twilio.com/docs/api/errors/20001", result) + finally: + sys.stderr = original_stderr + + def test_string_representation_tty_with_validation_errors(self): + """Test __str__ method for TTY with validation errors (colored)""" + errors = [ + {"detail": "must be positive", "pointer": "#/age"}, + {"detail": "must be valid", "pointer": "#/email"}, + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Validation Failed", + status=422, + code=20001, + errors=errors, + method="POST", + uri="/api/v1/users", + ) + + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=True) + + result = str(exc) + + self.assertIn("Validation Errors", result) + self.assertIn("#/age", result) + self.assertIn("must be positive", result) + self.assertIn("#/email", result) + self.assertIn("must be valid", result) + finally: + sys.stderr = original_stderr + + def test_string_representation_tty_no_uri(self): + """Test __str__ method when uri is empty""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Error", + status=400, + code=20001, + method="GET", + uri="", + ) + + import sys + + original_stderr = sys.stderr + try: + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=True) + + result = str(exc) + + self.assertIn("(no URI)", result) + finally: + sys.stderr = original_stderr + + def test_validation_errors_with_missing_fields(self): + """Test validation errors with missing detail or pointer fields""" + errors = [ + {"detail": "error detail"}, # missing pointer + {"pointer": "#/field"}, # missing detail + {}, # both missing + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Validation Failed", + status=422, + code=20001, + errors=errors, + ) + + import sys + + original_stderr = sys.stderr + try: + # Test non-TTY output + sys.stderr = Mock() + sys.stderr.isatty = Mock(return_value=False) + + result = str(exc) + # Should handle missing fields gracefully + self.assertIn("Validation errors", result) + finally: + sys.stderr = original_stderr + + def test_multiple_validation_errors(self): + """Test with multiple validation errors""" + errors = [ + {"detail": "Field is required", "pointer": "#/firstName"}, + {"detail": "Must be at least 18", "pointer": "#/age"}, + {"detail": "Invalid format", "pointer": "#/phoneNumber"}, + {"detail": "Must be unique", "pointer": "#/email"}, + ] + + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Validation Failed", + status=422, + code=20001, + errors=errors, + ) + + self.assertEqual(len(exc.errors), 4) + self.assertEqual(exc.errors[2]["pointer"], "#/phoneNumber") + self.assertEqual(exc.errors[3]["detail"], "Must be unique") + + def test_exception_as_parent_class(self): + """Test that TwilioServiceException is a proper exception""" + exc = TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Error", + status=400, + code=20001, + ) + + self.assertIsInstance(exc, Exception) + self.assertIsInstance(exc, TwilioException) + + def test_exception_can_be_raised_and_caught(self): + """Test that TwilioServiceException can be raised and caught""" + with self.assertRaises(TwilioServiceException) as context: + raise TwilioServiceException( + type_uri="https://www.twilio.com/docs/api/errors/20001", + title="Test Error", + status=400, + code=20001, + ) + + self.assertEqual(context.exception.title, "Test Error") + self.assertEqual(context.exception.code, 20001) + + +class ResponseInfoIntegrationTestCase(IntegrationTestCase): + """Integration tests for *_with_response_info methods""" + + def test_fetch_with_response_info(self): + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123", "name": "Test Account"}', + {"X-Custom-Header": "test-value"}, + ), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(payload["name"], "Test Account") + self.assertEqual(status_code, 200) + self.assertIn("X-Custom-Header", headers) + self.assertEqual(headers["X-Custom-Header"], "test-value") + + def test_update_with_response_info(self): + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123", "name": "Updated Account"}', + {"X-Update-Header": "updated"}, + ), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123.json", + ), + ) + payload, status_code, headers = self.client.api.v2010.update_with_response_info( + method="POST", uri="/Accounts/AC123.json", data={"name": "Updated Account"} + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(payload["name"], "Updated Account") + self.assertEqual(status_code, 200) + self.assertIn("X-Update-Header", headers) + + def test_delete_with_response_info(self): + self.holodeck.mock( + Response(204, "", {"X-Delete-Header": "deleted"}), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + success, status_code, headers = self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + + self.assertTrue(success) + self.assertEqual(status_code, 204) + self.assertIn("X-Delete-Header", headers) + + def test_create_with_response_info(self): + self.holodeck.mock( + Response( + 201, + '{"sid": "MM123", "body": "Hello World"}', + {"X-Create-Header": "created"}, + ), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json", + ), + ) + payload, status_code, headers = self.client.api.v2010.create_with_response_info( + method="POST", + uri="/Accounts/AC123/Messages.json", + data={"body": "Hello World"}, + ) + + self.assertEqual(payload["sid"], "MM123") + self.assertEqual(payload["body"], "Hello World") + self.assertEqual(status_code, 201) + self.assertIn("X-Create-Header", headers) + + def test_page_with_response_info(self): + self.holodeck.mock( + Response( + 200, + '{"messages": [], "next_page_uri": null}', + {"X-Page-Header": "page"}, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json" + ), + ) + response, status_code, headers = self.client.api.v2010.page_with_response_info( + method="GET", uri="/Accounts/AC123/Messages.json" + ) + + self.assertIsNotNone(response) + self.assertEqual(status_code, 200) + self.assertIn("X-Page-Header", headers) + + def test_fetch_with_response_info_error(self): + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC456.json"), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC456.json" + ) + + self.assertIn("Unable to fetch record", str(context.exception)) + + def test_update_with_response_info_error(self): + self.holodeck.mock( + Response(400, '{"message": "Invalid request"}'), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123.json", + ), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.update_with_response_info( + method="POST", uri="/Accounts/AC123.json", data={"invalid": "data"} + ) + + self.assertIn("Unable to update record", str(context.exception)) + + def test_delete_with_response_info_error(self): + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM456.json", + ), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Messages/MM456.json" + ) + + self.assertIn("Unable to delete record", str(context.exception)) + + def test_delete_with_response_info_json_body(self): + """Test delete_with_response_info with JSON response body""" + self.holodeck.mock( + Response( + 202, + '{"sid": "DE123", "status": "deleted", "account_sid": "AC123"}', + {"X-Delete-Header": "deleted", "X-Request-Id": "req123"}, + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result, status_code, headers = self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + + self.assertIsInstance(result, dict) + self.assertEqual(result["sid"], "DE123") + self.assertEqual(result["status"], "deleted") + self.assertEqual(result["account_sid"], "AC123") + self.assertEqual(status_code, 202) + self.assertIn("X-Delete-Header", headers) + self.assertEqual(headers["X-Delete-Header"], "deleted") + self.assertIn("X-Request-Id", headers) + + def test_delete_with_response_info_no_content(self): + """Test delete_with_response_info with no content (returns boolean)""" + self.holodeck.mock( + Response(204, "", {"X-Delete-Header": "success"}), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + result, status_code, headers = self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + + self.assertTrue(result) + self.assertIsInstance(result, bool) + self.assertEqual(status_code, 204) + self.assertIn("X-Delete-Header", headers) + + def test_delete_with_response_info_invalid_json(self): + """Test delete_with_response_info with invalid JSON content""" + self.holodeck.mock( + Response( + 200, + "Not valid JSON", + {"X-Delete-Header": "deleted"}, + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result, status_code, headers = self.client.api.v2010.delete_with_response_info( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + + # Should fallback to boolean True when JSON parsing fails + self.assertTrue(result) + self.assertIsInstance(result, bool) + self.assertEqual(status_code, 200) + self.assertIn("X-Delete-Header", headers) + + def test_create_with_response_info_error(self): + self.holodeck.mock( + Response(400, '{"message": "Invalid request"}'), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json", + ), + ) + + with self.assertRaises(Exception) as context: + self.client.api.v2010.create_with_response_info( + method="POST", + uri="/Accounts/AC123/Messages.json", + data={"invalid": "data"}, + ) + + self.assertIn("Unable to create record", str(context.exception)) + + def test_fetch_with_response_info_empty_headers(self): + self.holodeck.mock( + Response(200, '{"sid": "AC123", "name": "Test Account"}', None), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(status_code, 200) + self.assertIsInstance(headers, dict) + self.assertEqual(len(headers), 0) + + def test_fetch_with_response_info_multiple_headers(self): + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123"}', + { + "X-Custom-Header-1": "value1", + "X-Custom-Header-2": "value2", + "Content-Type": "application/json", + }, + ), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertEqual(status_code, 200) + self.assertIn("X-Custom-Header-1", headers) + self.assertIn("X-Custom-Header-2", headers) + self.assertIn("Content-Type", headers) + self.assertEqual(headers["X-Custom-Header-1"], "value1") + self.assertEqual(headers["X-Custom-Header-2"], "value2") + + def test_fetch_with_response_info_returns_tuple(self): + self.holodeck.mock( + Response(200, '{"sid": "AC123"}', {"X-Test": "test"}), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + result = self.client.api.v2010.fetch_with_response_info( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertIsInstance(result, tuple) + self.assertEqual(len(result), 3) + payload, status_code, headers = result + self.assertIsInstance(payload, dict) + self.assertIsInstance(status_code, int) + self.assertIsInstance(headers, dict) + + +class AsyncVersionTestCase(aiounittest.AsyncTestCase): + def setUp(self): + from tests.holodeck import AsyncHolodeck + from twilio.rest import Client + + self.holodeck = AsyncHolodeck() + self.client = Client( + "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "AUTHTOKEN", http_client=self.holodeck + ) + + async def test_fetch_with_response_info_async(self): + """Test fetch_with_response_info_async method""" + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123", "name": "Test Account"}', + {"X-Custom-Header": "test-value"}, + ), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = ( + await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC123.json" + ) + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(payload["name"], "Test Account") + self.assertEqual(status_code, 200) + self.assertIn("X-Custom-Header", headers) + self.assertEqual(headers["X-Custom-Header"], "test-value") + + async def test_update_with_response_info_async(self): + """Test update_with_response_info_async method""" + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123", "name": "Updated Account"}', + {"X-Update-Header": "updated"}, + ), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123.json", + ), + ) + payload, status_code, headers = ( + await self.client.api.v2010.update_with_response_info_async( + method="POST", + uri="/Accounts/AC123.json", + data={"name": "Updated Account"}, + ) + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(payload["name"], "Updated Account") + self.assertEqual(status_code, 200) + self.assertIn("X-Update-Header", headers) + + async def test_delete_with_response_info_async(self): + """Test delete_with_response_info_async method""" + self.holodeck.mock( + Response(204, "", {"X-Delete-Header": "deleted"}), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + success, status_code, headers = ( + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + ) + + self.assertTrue(success) + self.assertEqual(status_code, 204) + self.assertIn("X-Delete-Header", headers) + + async def test_create_with_response_info_async(self): + """Test create_with_response_info_async method""" + self.holodeck.mock( + Response( + 201, + '{"sid": "MM123", "body": "Hello World"}', + {"X-Create-Header": "created"}, + ), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json", + ), + ) + payload, status_code, headers = ( + await self.client.api.v2010.create_with_response_info_async( + method="POST", + uri="/Accounts/AC123/Messages.json", + data={"body": "Hello World"}, + ) + ) + + self.assertEqual(payload["sid"], "MM123") + self.assertEqual(payload["body"], "Hello World") + self.assertEqual(status_code, 201) + self.assertIn("X-Create-Header", headers) + + async def test_page_with_response_info_async(self): + """Test page_with_response_info_async method""" + self.holodeck.mock( + Response( + 200, + '{"messages": [], "next_page_uri": null}', + {"X-Page-Header": "page"}, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json" + ), + ) + response, status_code, headers = ( + await self.client.api.v2010.page_with_response_info_async( + method="GET", uri="/Accounts/AC123/Messages.json" + ) + ) + + self.assertIsNotNone(response) + self.assertEqual(status_code, 200) + self.assertIn("X-Page-Header", headers) + + async def test_fetch_with_response_info_async_error(self): + """Test fetch_with_response_info_async method with error""" + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC456.json"), + ) + + with self.assertRaises(Exception) as context: + await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC456.json" + ) + + self.assertIn("Unable to fetch record", str(context.exception)) + + async def test_update_with_response_info_async_error(self): + """Test update_with_response_info_async method with error""" + self.holodeck.mock( + Response(400, '{"message": "Invalid request"}'), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123.json", + ), + ) + + with self.assertRaises(Exception) as context: + await self.client.api.v2010.update_with_response_info_async( + method="POST", uri="/Accounts/AC123.json", data={"invalid": "data"} + ) + + self.assertIn("Unable to update record", str(context.exception)) + + async def test_delete_with_response_info_async_error(self): + """Test delete_with_response_info_async method with error""" + self.holodeck.mock( + Response(404, '{"message": "Resource not found"}'), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM456.json", + ), + ) + + with self.assertRaises(Exception) as context: + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Messages/MM456.json" + ) + + self.assertIn("Unable to delete record", str(context.exception)) + + async def test_delete_with_response_info_async_json_body(self): + """Test delete_with_response_info_async with JSON response body""" + self.holodeck.mock( + Response( + 202, + '{"sid": "DE123", "status": "deleted", "account_sid": "AC123"}', + {"X-Delete-Header": "deleted", "X-Request-Id": "req123"}, + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result, status_code, headers = ( + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + ) + + self.assertIsInstance(result, dict) + self.assertEqual(result["sid"], "DE123") + self.assertEqual(result["status"], "deleted") + self.assertEqual(result["account_sid"], "AC123") + self.assertEqual(status_code, 202) + self.assertIn("X-Delete-Header", headers) + self.assertEqual(headers["X-Delete-Header"], "deleted") + self.assertIn("X-Request-Id", headers) + + async def test_delete_with_response_info_async_no_content(self): + """Test delete_with_response_info_async with no content (returns boolean)""" + self.holodeck.mock( + Response(204, "", {"X-Delete-Header": "success"}), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages/MM123.json", + ), + ) + result, status_code, headers = ( + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Messages/MM123.json" + ) + ) + + self.assertTrue(result) + self.assertIsInstance(result, bool) + self.assertEqual(status_code, 204) + self.assertIn("X-Delete-Header", headers) + + async def test_delete_with_response_info_async_invalid_json(self): + """Test delete_with_response_info_async with invalid JSON content""" + self.holodeck.mock( + Response( + 200, + "Not valid JSON", + {"X-Delete-Header": "deleted"}, + ), + Request( + method="DELETE", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Resources/DE123.json", + ), + ) + result, status_code, headers = ( + await self.client.api.v2010.delete_with_response_info_async( + method="DELETE", uri="/Accounts/AC123/Resources/DE123.json" + ) + ) + + # Should fallback to boolean True when JSON parsing fails + self.assertTrue(result) + self.assertIsInstance(result, bool) + self.assertEqual(status_code, 200) + self.assertIn("X-Delete-Header", headers) + + async def test_create_with_response_info_async_error(self): + """Test create_with_response_info_async method with error""" + self.holodeck.mock( + Response(400, '{"message": "Invalid request"}'), + Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json", + ), + ) + + with self.assertRaises(Exception) as context: + await self.client.api.v2010.create_with_response_info_async( + method="POST", + uri="/Accounts/AC123/Messages.json", + data={"invalid": "data"}, + ) + + self.assertIn("Unable to create record", str(context.exception)) + + async def test_fetch_with_response_info_async_empty_headers(self): + """Test fetch_with_response_info_async with None headers""" + self.holodeck.mock( + Response(200, '{"sid": "AC123", "name": "Test Account"}', None), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = ( + await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC123.json" + ) + ) + + self.assertEqual(payload["sid"], "AC123") + self.assertEqual(status_code, 200) + self.assertIsInstance(headers, dict) + self.assertEqual(len(headers), 0) + + async def test_fetch_with_response_info_async_multiple_headers(self): + """Test fetch_with_response_info_async with multiple headers""" + self.holodeck.mock( + Response( + 200, + '{"sid": "AC123"}', + { + "X-Custom-Header-1": "value1", + "X-Custom-Header-2": "value2", + "Content-Type": "application/json", + }, + ), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + payload, status_code, headers = ( + await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC123.json" + ) + ) + + self.assertEqual(status_code, 200) + self.assertIn("X-Custom-Header-1", headers) + self.assertIn("X-Custom-Header-2", headers) + self.assertIn("Content-Type", headers) + self.assertEqual(headers["X-Custom-Header-1"], "value1") + self.assertEqual(headers["X-Custom-Header-2"], "value2") + + async def test_fetch_with_response_info_async_returns_tuple(self): + """Test that fetch_with_response_info_async returns proper tuple structure""" + self.holodeck.mock( + Response(200, '{"sid": "AC123"}', {"X-Test": "test"}), + Request(url="https://api.twilio.com/2010-04-01/Accounts/AC123.json"), + ) + result = await self.client.api.v2010.fetch_with_response_info_async( + method="GET", uri="/Accounts/AC123.json" + ) + + self.assertIsInstance(result, tuple) + self.assertEqual(len(result), 3) + payload, status_code, headers = result + self.assertIsInstance(payload, dict) + self.assertIsInstance(status_code, int) + self.assertIsInstance(headers, dict) diff --git a/tests/unit/http/test_api_response.py b/tests/unit/http/test_api_response.py new file mode 100644 index 0000000000..4a1572b24c --- /dev/null +++ b/tests/unit/http/test_api_response.py @@ -0,0 +1,96 @@ +import unittest +from twilio.base.api_response import ApiResponse + + +class TestApiResponse(unittest.TestCase): + def test_initialization(self): + """Test ApiResponse initialization""" + data = {"sid": "AC123", "friendly_name": "Test"} + response = ApiResponse( + data=data, status_code=200, headers={"Content-Type": "application/json"} + ) + + self.assertEqual(response.data, data) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.headers["Content-Type"], "application/json") + + def test_repr(self): + """Test string representation""" + response = ApiResponse(data={"test": "data"}, status_code=201, headers={}) + repr_str = repr(response) + self.assertIn("201", repr_str) + self.assertIn("dict", repr_str) + + def test_str(self): + """Test human-readable string representation""" + response = ApiResponse(data={"test": "data"}, status_code=200, headers={}) + str_repr = str(response) + self.assertIn("200", str_repr) + self.assertIn("dict", str_repr) + + def test_with_list_data(self): + """Test ApiResponse with list data""" + data = [{"sid": "AC1"}, {"sid": "AC2"}] + response = ApiResponse(data=data, status_code=200, headers={}) + self.assertEqual(len(response.data), 2) + self.assertEqual(response.status_code, 200) + + def test_with_boolean_data(self): + """Test ApiResponse with boolean data (delete operations)""" + response = ApiResponse(data=True, status_code=204, headers={}) + self.assertTrue(response.data) + self.assertEqual(response.status_code, 204) + + def test_with_different_status_codes(self): + """Test ApiResponse with various status codes""" + # Test 201 Created + response_201 = ApiResponse(data={"created": True}, status_code=201, headers={}) + self.assertEqual(response_201.status_code, 201) + + # Test 204 No Content + response_204 = ApiResponse(data=True, status_code=204, headers={}) + self.assertEqual(response_204.status_code, 204) + + # Test 200 OK + response_200 = ApiResponse(data={"ok": True}, status_code=200, headers={}) + self.assertEqual(response_200.status_code, 200) + + def test_headers_access(self): + """Test accessing various headers""" + headers = { + "Content-Type": "application/json", + "X-RateLimit-Remaining": "100", + "X-RateLimit-Limit": "1000", + } + response = ApiResponse(data={"test": "data"}, status_code=200, headers=headers) + + self.assertEqual(response.headers["Content-Type"], "application/json") + self.assertEqual(response.headers["X-RateLimit-Remaining"], "100") + self.assertEqual(response.headers["X-RateLimit-Limit"], "1000") + + def test_empty_headers(self): + """Test ApiResponse with empty headers""" + response = ApiResponse(data={"test": "data"}, status_code=200, headers={}) + self.assertEqual(response.headers, {}) + + def test_data_attribute_types(self): + """Test that data attribute can hold various types""" + # Dictionary data + dict_response = ApiResponse(data={"key": "value"}, status_code=200, headers={}) + self.assertIsInstance(dict_response.data, dict) + + # List data + list_response = ApiResponse(data=[1, 2, 3], status_code=200, headers={}) + self.assertIsInstance(list_response.data, list) + + # Boolean data + bool_response = ApiResponse(data=True, status_code=204, headers={}) + self.assertIsInstance(bool_response.data, bool) + + # None data + none_response = ApiResponse(data=None, status_code=204, headers={}) + self.assertIsNone(none_response.data) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/http/test_async_http_client.py b/tests/unit/http/test_async_http_client.py index df43606843..23df35dc02 100644 --- a/tests/unit/http/test_async_http_client.py +++ b/tests/unit/http/test_async_http_client.py @@ -10,10 +10,11 @@ class MockResponse(object): A mock of the aiohttp.ClientResponse class """ - def __init__(self, text, status): + def __init__(self, text, status, method="GET"): self._text = text self.status = status self.headers = {} + self.method = method async def text(self): return self._text diff --git a/tests/unit/http/test_http_client.py b/tests/unit/http/test_http_client.py index 8484e57b17..9a74139d40 100644 --- a/tests/unit/http/test_http_client.py +++ b/tests/unit/http/test_http_client.py @@ -10,6 +10,7 @@ from twilio.base.version import Version from twilio.http.http_client import TwilioHttpClient from twilio.http.response import Response +from twilio.http.request import Request class TestHttpClientRequest(unittest.TestCase): @@ -293,6 +294,43 @@ def test_session_not_preserved(self): self.assertEqual(response_2.content, "response_2") +class TestTwilioRequest(unittest.TestCase): + def test_str(self): + + req = Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts.json", + auth=("AC123", "token"), + params={"PageSize": "1"}, + data={"FriendlyName": "My New Account"}, + headers={"X-Custom-Header": "Value"}, + ) + expected = ( + "POST https://api.twilio.com/2010-04-01/Accounts.json?PageSize=1\n" + ' -d "FriendlyName=My New Account"\n' + ' -H "X-Custom-Header: Value"' + ) + self.assertEqual(expected, req.__str__()) + + def test_str_excludes_authorization_header(self): + req = Request( + method="POST", + url="https://api.twilio.com/2010-04-01/Accounts.json", + params={"PageSize": "1"}, + data={"FriendlyName": "My New Account"}, + headers={ + "Authorization": "Bearer secret-token", + "X-Custom-Header": "Value", + }, + ) + expected = ( + "POST https://api.twilio.com/2010-04-01/Accounts.json?PageSize=1\n" + ' -d "FriendlyName=My New Account"\n' + ' -H "X-Custom-Header: Value"' + ) + self.assertEqual(expected, req.__str__()) + + class MyVersion(Version): def __init__(self, domain): super().__init__(domain, "v1") diff --git a/tests/unit/rest/test_client.py b/tests/unit/rest/test_client.py index 9623dc52ad..5b1f047255 100644 --- a/tests/unit/rest/test_client.py +++ b/tests/unit/rest/test_client.py @@ -1,7 +1,9 @@ import unittest + import aiounittest from mock import AsyncMock, Mock + from twilio.http.response import Response from twilio.rest import Client @@ -18,16 +20,16 @@ def test_set_client_edge_default_region(self): ) def test_set_client_region(self): - self.client.region = "region" + self.client.region = "us1" self.assertEqual( self.client.get_hostname("https://api.twilio.com"), - "https://api.region.twilio.com", + "https://api.us1.twilio.com", ) def test_set_uri_region(self): self.assertEqual( - self.client.get_hostname("https://api.region.twilio.com"), - "https://api.region.twilio.com", + self.client.get_hostname("https://api.us1.twilio.com"), + "https://api.us1.twilio.com", ) def test_set_client_edge_region(self): @@ -79,9 +81,21 @@ def test_periods_in_query(self): class TestUserAgentClients(unittest.TestCase): def setUp(self): self.client = Client("username", "password") + mock_response = Mock() + mock_response.status_code = 200 + mock_response.text = "" + mock_response.headers = {} + self.client.http_client.session = Mock() + self.client.http_client.session.prepare_request = Mock( + side_effect=lambda r: r + ) + self.client.http_client.session.merge_environment_settings = Mock( + return_value={} + ) + self.client.http_client.session.send = Mock(return_value=mock_response) def tearDown(self): - self.client.http_client.session.close() + pass def test_set_default_user_agent(self): self.client.request("GET", "https://api.twilio.com/") diff --git a/twilio/__init__.py b/twilio/__init__.py index bb8cd36f5d..f089e67949 100644 --- a/twilio/__init__.py +++ b/twilio/__init__.py @@ -1,2 +1,2 @@ -__version_info__ = ("9", "2", "3") +__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 5f17c75406..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 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/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 9d329c6aa7..2f2d363535 100644 --- a/twilio/http/http_client.py +++ b/twilio/http/http_client.py @@ -40,7 +40,7 @@ def __init__( self.session = Session() if pool_connections else None if self.session and max_retries is not None: self.session.mount("https://", HTTPAdapter(max_retries=max_retries)) - if self.session is not None: + elif self.session is not None: self.session.mount( "https://", HTTPAdapter(pool_maxsize=min(32, os.cpu_count() + 4)) ) @@ -88,10 +88,11 @@ def request( } 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) @@ -102,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 1a4a83f0a5..4a376c7f4f 100644 --- a/twilio/http/validation_client.py +++ b/twilio/http/validation_client.py @@ -8,7 +8,6 @@ from twilio.http.response import Response from twilio.jwt.validation import ClientValidationJwt - ValidationPayload = namedtuple( "ValidationPayload", ["method", "path", "query_string", "all_headers", "signed_headers", "body"], diff --git a/twilio/jwt/__init__.py b/twilio/jwt/__init__.py index 7a51ea70d5..c17b548516 100644 --- a/twilio/jwt/__init__.py +++ b/twilio/jwt/__init__.py @@ -1,7 +1,6 @@ import jwt as jwt_lib import time - __all__ = ["Jwt", "JwtDecodeError"] diff --git a/twilio/rest/__init__.py b/twilio/rest/__init__.py index 31d114a6c0..fe898b2095 100644 --- a/twilio/rest/__init__.py +++ b/twilio/rest/__init__.py @@ -16,6 +16,7 @@ if TYPE_CHECKING: from twilio.rest.accounts import Accounts from twilio.rest.api import Api + from twilio.rest.assistants import Assistants from twilio.rest.bulkexports import Bulkexports from twilio.rest.chat import Chat from twilio.rest.content import Content @@ -24,13 +25,16 @@ 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.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 @@ -95,6 +99,7 @@ def __init__( environment=None, edge=None, user_agent_extensions=None, + credential_provider=None, ): """ Initializes the Twilio Client @@ -120,11 +125,13 @@ def __init__( environment, edge, user_agent_extensions, + credential_provider, ) # Domains self._accounts: Optional["Accounts"] = None self._api: Optional["Api"] = None + self._assistants: Optional["Assistants"] = None self._bulkexports: Optional["Bulkexports"] = None self._chat: Optional["Chat"] = None self._content: Optional["Content"] = None @@ -133,13 +140,16 @@ def __init__( 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._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 @@ -186,6 +196,19 @@ def api(self) -> "Api": self._api = Api(self) return self._api + @property + def assistants(self) -> "Assistants": + """ + Access the Assistants Twilio Domain + + :returns: Assistants Twilio Domain + """ + if self._assistants is None: + from twilio.rest.assistants import Assistants + + self._assistants = Assistants(self) + return self._assistants + @property def bulkexports(self) -> "Bulkexports": """ @@ -290,6 +313,32 @@ def preview_iam(self) -> "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": """ @@ -329,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": """ @@ -355,6 +417,19 @@ def marketplace(self) -> "Marketplace": self._marketplace = Marketplace(self) return self._marketplace + @property + def memory(self) -> "Memory": + """ + Access the Memory Twilio Domain + + :returns: Memory Twilio Domain + """ + if self._memory is None: + from twilio.rest.memory import Memory + + self._memory = Memory(self) + return self._memory + @property def messaging(self) -> "Messaging": """ @@ -368,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/v1/__init__.py b/twilio/rest/accounts/v1/__init__.py index 142d5c7a96..8be121c71e 100644 --- a/twilio/rest/accounts/v1/__init__.py +++ b/twilio/rest/accounts/v1/__init__.py @@ -16,7 +16,10 @@ 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 @@ -31,7 +34,10 @@ 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 @@ -41,12 +47,30 @@ 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: diff --git a/twilio/rest/accounts/v1/auth_token_promotion.py b/twilio/rest/accounts/v1/auth_token_promotion.py index 7ab6c3f39d..c60ea48baa 100644 --- a/twilio/rest/accounts/v1/auth_token_promotion.py +++ b/twilio/rest/accounts/v1/auth_token_promotion.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,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 @@ -99,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 @@ -106,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: """ @@ -123,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: """ 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/aws.py b/twilio/rest/accounts/v1/credential/aws.py index 05d92755c4..0c81106aec 100644 --- a/twilio/rest/accounts/v1/credential/aws.py +++ b/twilio/rest/accounts/v1/credential/aws.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AwsContext] = None @property @@ -86,6 +88,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AwsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AwsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AwsInstance": """ Fetch the AwsInstance @@ -104,6 +124,24 @@ async def fetch_async(self) -> "AwsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AwsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AwsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, friendly_name: Union[str, object] = values.unset) -> "AwsInstance": """ Update the AwsInstance @@ -130,6 +168,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the AwsInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AwsInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -157,6 +223,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/AWS/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AwsInstance @@ -164,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: @@ -176,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: @@ -188,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: """ @@ -207,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" - 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) -> 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" + + 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 + ) -> 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 @@ -283,6 +501,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AwsInstance: :param payload: Payload response from the API """ + return AwsInstance(self._version, payload) def __repr__(self) -> str: @@ -307,20 +526,17 @@ def __init__(self, version: Version): self._uri = "/Credentials/AWS" - def create( + def _create( self, credentials: str, friendly_name: Union[str, object] = values.unset, account_sid: Union[str, object] = values.unset, - ) -> AwsInstance: + ) -> tuple: """ - Create the AwsInstance - - :param credentials: A string that contains the AWS access credentials in the format `:`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request. + Internal helper for create operation - :returns: The created AwsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -332,20 +548,22 @@ def create( ) headers = values.of({"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 AwsInstance(self._version, payload) - - async def create_async( + def create( self, credentials: str, friendly_name: Union[str, object] = values.unset, account_sid: Union[str, object] = values.unset, ) -> AwsInstance: """ - Asynchronously create the AwsInstance + Create the AwsInstance :param credentials: A string that contains the AWS access credentials in the format `:`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. @@ -353,6 +571,48 @@ async def create_async( :returns: The created AwsInstance """ + payload, _, _ = self._create( + credentials=credentials, + friendly_name=friendly_name, + account_sid=account_sid, + ) + return AwsInstance(self._version, payload) + + def create_with_http_info( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the AwsInstance and return response metadata + + :param credentials: A string that contains the AWS access credentials in the format `:`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + credentials=credentials, + friendly_name=friendly_name, + account_sid=account_sid, + ) + instance = AwsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -363,12 +623,59 @@ async def create_async( ) headers = values.of({"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, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> AwsInstance: + """ + Asynchronously create the AwsInstance + + :param credentials: A string that contains the AWS access credentials in the format `:`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request. + + :returns: The created AwsInstance + """ + payload, _, _ = await self._create_async( + credentials=credentials, + friendly_name=friendly_name, + account_sid=account_sid, + ) return AwsInstance(self._version, payload) + async def create_with_http_info_async( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the AwsInstance and return response metadata + + :param credentials: A string that contains the AWS access credentials in the format `:`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + credentials=credentials, + friendly_name=friendly_name, + account_sid=account_sid, + ) + instance = AwsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -419,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, @@ -438,6 +795,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -464,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( @@ -472,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, @@ -496,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( @@ -523,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 ec2a1f8660..1e5333fe17 100644 --- a/twilio/rest/accounts/v1/credential/public_key.py +++ b/twilio/rest/accounts/v1/credential/public_key.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PublicKeyContext] = None @property @@ -86,6 +88,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PublicKeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PublicKeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "PublicKeyInstance": """ Fetch the PublicKeyInstance @@ -104,6 +124,24 @@ async def fetch_async(self) -> "PublicKeyInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PublicKeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PublicKeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset ) -> "PublicKeyInstance": @@ -132,6 +170,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PublicKeyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PublicKeyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -159,6 +225,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/PublicKeys/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PublicKeyInstance @@ -166,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: @@ -178,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: @@ -190,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: """ @@ -209,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 @@ -231,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 @@ -255,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: """ @@ -287,6 +505,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PublicKeyInstance: :param payload: Payload response from the API """ + return PublicKeyInstance(self._version, payload) def __repr__(self) -> str: @@ -311,20 +530,17 @@ def __init__(self, version: Version): self._uri = "/Credentials/PublicKeys" - def create( + def _create( self, public_key: str, friendly_name: Union[str, object] = values.unset, account_sid: Union[str, object] = values.unset, - ) -> PublicKeyInstance: + ) -> tuple: """ - Create the PublicKeyInstance + Internal helper for create operation - :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request - - :returns: The created PublicKeyInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -336,20 +552,22 @@ def create( ) headers = values.of({"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 PublicKeyInstance(self._version, payload) - - async def create_async( + def create( self, public_key: str, friendly_name: Union[str, object] = values.unset, account_sid: Union[str, object] = values.unset, ) -> PublicKeyInstance: """ - Asynchronously create the PublicKeyInstance + Create the PublicKeyInstance :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. @@ -357,6 +575,44 @@ async def create_async( :returns: The created PublicKeyInstance """ + payload, _, _ = self._create( + public_key=public_key, friendly_name=friendly_name, account_sid=account_sid + ) + return PublicKeyInstance(self._version, payload) + + def create_with_http_info( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the PublicKeyInstance and return response metadata + + :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + public_key=public_key, friendly_name=friendly_name, account_sid=account_sid + ) + instance = PublicKeyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -367,12 +623,55 @@ async def create_async( ) headers = values.of({"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, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> PublicKeyInstance: + """ + Asynchronously create the PublicKeyInstance + + :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request + + :returns: The created PublicKeyInstance + """ + payload, _, _ = await self._create_async( + public_key=public_key, friendly_name=friendly_name, account_sid=account_sid + ) return PublicKeyInstance(self._version, payload) + async def create_with_http_info_async( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the PublicKeyInstance and return response metadata + + :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + public_key=public_key, friendly_name=friendly_name, account_sid=account_sid + ) + instance = PublicKeyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -423,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, @@ -442,6 +791,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -468,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( @@ -476,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, @@ -500,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( @@ -527,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 index 51f00fd8ca..f7e7912dde 100644 --- a/twilio/rest/accounts/v1/safelist.py +++ b/twilio/rest/accounts/v1/safelist.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,7 +24,7 @@ class SafelistInstance(InstanceResource): """ :ivar sid: The unique string that we created to identify the SafeList resource. - :ivar phone_number: The phone number in SafeList. + :ivar phone_number: The phone number or phone number 1k prefix in SafeList. """ def __init__(self, version: Version, payload: Dict[str, Any]): @@ -55,13 +56,12 @@ def __init__(self, version: Version): self._uri = "/SafeList/Numbers" - def create(self, phone_number: str) -> SafelistInstance: + def _create(self, phone_number: str) -> tuple: """ - Create the SafelistInstance + Internal helper for create operation - :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). - - :returns: The created SafelistInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -71,19 +71,43 @@ def create(self, phone_number: str) -> SafelistInstance: ) headers = values.of({"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, phone_number: str) -> SafelistInstance: + """ + Create the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: The created SafelistInstance + """ + payload, _, _ = self._create(phone_number=phone_number) return SafelistInstance(self._version, payload) - async def create_async(self, phone_number: str) -> SafelistInstance: + def create_with_http_info(self, phone_number: str) -> ApiResponse: """ - Asynchronously create the SafelistInstance + Create the SafelistInstance and return response metadata - :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param phone_number: The phone number or phone number 1k prefix to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). - :returns: The created SafelistInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(phone_number=phone_number) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, phone_number: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -93,19 +117,88 @@ async def create_async(self, phone_number: str) -> SafelistInstance: ) headers = values.of({"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, 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: """ - Asynchronously delete the SafelistInstance + Delete the SafelistInstance - :param phone_number: The phone number to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param phone_number: The phone number or phone number 1k prefix to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(phone_number=phone_number) + return success + + def delete_with_http_info( + self, phone_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Delete the SafelistInstance and return response metadata + + :param phone_number: The phone number or phone number 1k prefix to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(phone_number=phone_number) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, phone_number: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) params = values.of( @@ -113,7 +206,7 @@ def delete(self, phone_number: Union[str, object] = values.unset) -> bool: "PhoneNumber": phone_number, } ) - return self._version.delete( + return await self._version.delete_with_response_info_async( method="DELETE", uri=self._uri, headers=headers, params=params ) @@ -123,65 +216,121 @@ async def delete_async( """ Asynchronously delete the SafelistInstance - :param phone_number: The phone number to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param phone_number: The phone number or phone number 1k prefix to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). :returns: True if delete succeeds, False otherwise """ + success, _, _ = 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 await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers, params=params + + 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: """ - Asynchronously fetch the SafelistInstance + Fetch the SafelistInstance - :param phone_number: The phone number to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param phone_number: The phone number or phone number 1k prefix to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). :returns: The fetched SafelistInstance """ + payload, _, _ = self._fetch(phone_number=phone_number) + return SafelistInstance(self._version, payload) + + def fetch_with_http_info( + self, phone_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the SafelistInstance and return response metadata + + :param phone_number: The phone number or phone number 1k prefix to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(phone_number=phone_number) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, phone_number: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Accept"] = "application/json" + params = values.of( { "PhoneNumber": phone_number, } ) - payload = self._version.fetch( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers, params=params ) - return SafelistInstance(self._version, payload) - async def fetch_async( self, phone_number: Union[str, object] = values.unset ) -> SafelistInstance: """ Asynchronously fetch the SafelistInstance - :param phone_number: The phone number to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param phone_number: The phone number or phone number 1k prefix to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). :returns: The fetched SafelistInstance """ - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + payload, _, _ = await self._fetch_async(phone_number=phone_number) + return SafelistInstance(self._version, payload) - params = values.of( - { - "PhoneNumber": phone_number, - } - ) + async def fetch_with_http_info_async( + self, phone_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the SafelistInstance and return response metadata - payload = await self._version.fetch_async( - method="GET", uri=self._uri, headers=headers, params=params + :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 ) - - return SafelistInstance(self._version, payload) + instance = SafelistInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ diff --git a/twilio/rest/accounts/v1/secondary_auth_token.py b/twilio/rest/accounts/v1/secondary_auth_token.py index 3735dd876a..9d79a739d7 100644 --- a/twilio/rest/accounts/v1/secondary_auth_token.py +++ b/twilio/rest/accounts/v1/secondary_auth_token.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,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 @@ -95,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 @@ -117,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 @@ -124,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: """ @@ -137,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: """ @@ -152,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: @@ -164,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: """ diff --git a/twilio/rest/api/v2010/account/__init__.py b/twilio/rest/api/v2010/account/__init__.py index dc0c53c9c0..0aa9ecd0b0 100644 --- a/twilio/rest/api/v2010/account/__init__.py +++ b/twilio/rest/api/v2010/account/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -99,6 +100,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AccountContext] = None @property @@ -134,6 +136,24 @@ async def fetch_async(self) -> "AccountInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccountInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccountInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -170,6 +190,42 @@ async def update_async( status=status, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Update the AccountInstance with HTTP info + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + status=status, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AccountInstance with HTTP info + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + status=status, + ) + @property def addresses(self) -> AddressList: """ @@ -390,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 @@ -397,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: """ @@ -416,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, @@ -441,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, @@ -469,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: @@ -790,6 +970,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AccountInstance: :param payload: Payload response from the API """ + return AccountInstance(self._version, payload) def __repr__(self) -> str: @@ -814,15 +995,12 @@ def __init__(self, version: Version): self._uri = "/Accounts.json" - def create( - self, friendly_name: Union[str, object] = values.unset - ) -> AccountInstance: + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: """ - Create the AccountInstance - - :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + Internal helper for create operation - :returns: The created AccountInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -832,22 +1010,50 @@ def create( ) headers = values.of({"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 AccountInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: Union[str, object] = values.unset ) -> AccountInstance: """ - Asynchronously create the AccountInstance + Create the AccountInstance :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` :returns: The created AccountInstance """ + payload, _, _ = self._create(friendly_name=friendly_name) + return AccountInstance(self._version, payload) + + def create_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the AccountInstance and return response metadata + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = AccountInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -856,12 +1062,43 @@ async def create_async( ) headers = values.of({"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, friendly_name: Union[str, object] = values.unset + ) -> AccountInstance: + """ + Asynchronously create the AccountInstance + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: The created AccountInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return AccountInstance(self._version, payload) + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the AccountInstance and return response metadata + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = AccountInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, friendly_name: Union[str, object] = values.unset, @@ -924,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, @@ -947,6 +1244,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -979,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( @@ -989,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, @@ -1019,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( @@ -1052,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 36ee8f2231..c309d54844 100644 --- a/twilio/rest/api/v2010/account/address/__init__.py +++ b/twilio/rest/api/v2010/account/address/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[AddressContext] = None @property @@ -115,6 +117,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AddressInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddressInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AddressInstance": """ Fetch the AddressInstance @@ -133,6 +153,24 @@ async def fetch_async(self) -> "AddressInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddressInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AddressInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -148,7 +186,7 @@ def update( """ Update the AddressInstance - :param friendly_name: A descriptive string that you create to describe the address. It can be up to 64 characters long. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. :param customer_name: The name to associate with the address. :param street: The number and street address of the address. :param city: The city of the address. @@ -187,7 +225,7 @@ async def update_async( """ Asynchronous coroutine to update the AddressInstance - :param friendly_name: A descriptive string that you create to describe the address. It can be up to 64 characters long. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. :param customer_name: The name to associate with the address. :param street: The number and street address of the address. :param city: The city of the address. @@ -211,6 +249,84 @@ async def update_async( street_secondary=street_secondary, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the AddressInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AddressInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + @property def dependent_phone_numbers(self) -> DependentPhoneNumberList: """ @@ -251,6 +367,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._dependent_phone_numbers: Optional[DependentPhoneNumberList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AddressInstance @@ -258,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: @@ -270,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: @@ -282,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: """ @@ -302,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, @@ -326,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, @@ -355,13 +561,54 @@ def update( "StreetSecondary": street_secondary, } ) + 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, + 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, @@ -369,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, @@ -380,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. @@ -394,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, @@ -409,22 +694,109 @@ async def update_async( "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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers ) - @property - def dependent_phone_numbers(self) -> DependentPhoneNumberList: + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Asynchronous coroutine to update the AddressInstance + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The updated AddressInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AddressInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + instance = AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def dependent_phone_numbers(self) -> DependentPhoneNumberList: """ Access the dependent_phone_numbers """ @@ -454,6 +826,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AddressInstance: :param payload: Payload response from the API """ + return AddressInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -485,7 +858,7 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Addresses.json".format(**self._solution) - def create( + def _create( self, customer_name: str, street: str, @@ -497,22 +870,12 @@ def create( emergency_enabled: Union[bool, object] = values.unset, auto_correct_address: Union[bool, object] = values.unset, street_secondary: Union[str, object] = values.unset, - ) -> AddressInstance: + ) -> tuple: """ - Create the AddressInstance + Internal helper for create operation - :param customer_name: The name to associate with the new address. - :param street: The number and street address of the new address. - :param city: The city of the new address. - :param region: The state or region of the new address. - :param postal_code: The postal code of the new address. - :param iso_country: The ISO country code of the new address. - :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long. - :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. - :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. - :param street_secondary: The additional number and street address of the address. - - :returns: The created AddressInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -531,15 +894,60 @@ def create( ) headers = values.of({"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, + customer_name: str, + street: str, + city: str, + region: str, + postal_code: str, + iso_country: str, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Create the AddressInstance + + :param customer_name: The name to associate with the new address. + :param street: The number and street address of the new address. + :param city: The city of the new address. + :param region: The state or region of the new address. + :param postal_code: The postal code of the new address. + :param iso_country: The ISO country code of the new address. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The created AddressInstance + """ + payload, _, _ = self._create( + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + iso_country=iso_country, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) return AddressInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, customer_name: str, street: str, @@ -551,9 +959,9 @@ async def create_async( emergency_enabled: Union[bool, object] = values.unset, auto_correct_address: Union[bool, object] = values.unset, street_secondary: Union[str, object] = values.unset, - ) -> AddressInstance: + ) -> ApiResponse: """ - Asynchronously create the AddressInstance + Create the AddressInstance and return response metadata :param customer_name: The name to associate with the new address. :param street: The number and street address of the new address. @@ -561,12 +969,48 @@ async def create_async( :param region: The state or region of the new address. :param postal_code: The postal code of the new address. :param iso_country: The ISO country code of the new address. - :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. :param street_secondary: The additional number and street address of the address. - :returns: The created AddressInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + iso_country=iso_country, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + instance = AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + customer_name: str, + street: str, + city: str, + region: str, + postal_code: str, + iso_country: str, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -585,18 +1029,110 @@ async def create_async( ) headers = values.of({"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, + customer_name: str, + street: str, + city: str, + region: str, + postal_code: str, + iso_country: str, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Asynchronously create the AddressInstance + + :param customer_name: The name to associate with the new address. + :param street: The number and street address of the new address. + :param city: The city of the new address. + :param region: The state or region of the new address. + :param postal_code: The postal code of the new address. + :param iso_country: The ISO country code of the new address. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The created AddressInstance + """ + payload, _, _ = await self._create_async( + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + iso_country=iso_country, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) return AddressInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, + customer_name: str, + street: str, + city: str, + region: str, + postal_code: str, + iso_country: str, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the AddressInstance and return response metadata + + :param customer_name: The name to associate with the new address. + :param street: The number and street address of the new address. + :param city: The city of the new address. + :param region: The state or region of the new address. + :param postal_code: The postal code of the new address. + :param iso_country: The ISO country code of the new address. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + iso_country=iso_country, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + instance = AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, customer_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, iso_country: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -609,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 @@ -623,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"], ) @@ -633,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, @@ -645,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 @@ -659,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, @@ -680,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 @@ -690,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, @@ -704,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, @@ -715,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 @@ -725,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, @@ -751,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 @@ -762,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, @@ -769,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, @@ -787,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 @@ -798,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, @@ -805,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: """ @@ -820,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: """ @@ -832,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 738f9baffd..9a21e34d7c 100644 --- a/twilio/rest/api/v2010/account/address/dependent_phone_number.py +++ b/twilio/rest/api/v2010/account/address/dependent_phone_number.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -134,6 +135,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DependentPhoneNumberInstance: :param payload: Payload response from the API """ + return DependentPhoneNumberInstance( self._version, payload, @@ -222,6 +224,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DependentPhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DependentPhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -241,6 +293,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -267,6 +320,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -275,6 +329,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DependentPhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DependentPhoneNumberInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -299,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, @@ -326,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, self._solution) + return DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DependentPhoneNumberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with DependentPhoneNumberPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> DependentPhoneNumberPage: """ @@ -341,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: """ @@ -353,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 d1e50c5f04..ba5a7926de 100644 --- a/twilio/rest/api/v2010/account/application.py +++ b/twilio/rest/api/v2010/account/application.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -94,6 +95,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[ApplicationContext] = None @property @@ -130,6 +132,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ApplicationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ApplicationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ApplicationInstance": """ Fetch the ApplicationInstance @@ -148,6 +168,24 @@ async def fetch_async(self) -> "ApplicationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApplicationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ApplicationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -268,6 +306,126 @@ async def update_async( public_application_connect_enabled=public_application_connect_enabled, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ApplicationInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ApplicationInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -299,6 +457,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ApplicationInstance @@ -306,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: @@ -318,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: @@ -330,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: """ @@ -350,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, @@ -381,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, @@ -428,21 +669,17 @@ def update( ), } ) + 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, @@ -462,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. @@ -483,43 +720,290 @@ 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": 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 - ), - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return ApplicationInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], + 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: """ @@ -539,6 +1023,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ApplicationInstance: :param payload: Payload response from the API """ + return ApplicationInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -558,19 +1043,266 @@ 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. + :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) + """ + + 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" - """ - super().__init__(version) + headers["Accept"] = "application/json" - # Path Solution - self._solution = { - "account_sid": account_sid, - } - self._uri = "/Accounts/{account_sid}/Applications.json".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, api_version: Union[str, object] = values.unset, voice_url: Union[str, object] = values.unset, @@ -590,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. @@ -611,42 +1343,29 @@ def create( :returns: The created ApplicationInstance """ - - data = values.of( - { - "ApiVersion": api_version, - "VoiceUrl": voice_url, - "VoiceMethod": voice_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceFallbackMethod": voice_fallback_method, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "VoiceCallerIdLookup": serialize.boolean_to_string( - voice_caller_id_lookup - ), - "SmsUrl": sms_url, - "SmsMethod": sms_method, - "SmsFallbackUrl": sms_fallback_url, - "SmsFallbackMethod": sms_fallback_method, - "SmsStatusCallback": sms_status_callback, - "MessageStatusCallback": message_status_callback, - "FriendlyName": friendly_name, - "PublicApplicationConnectEnabled": serialize.boolean_to_string( - public_application_connect_enabled - ), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = await self._create_async( + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + friendly_name=friendly_name, + public_application_connect_enabled=public_application_connect_enabled, ) - return ApplicationInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + async def create_with_http_info_async( self, api_version: Union[str, object] = values.unset, voice_url: Union[str, object] = values.unset, @@ -664,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. @@ -685,42 +1404,30 @@ async def create_async( :param friendly_name: A descriptive string that you create to describe the new application. It can be up to 64 characters long. :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. - :returns: The created ApplicationInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "ApiVersion": api_version, - "VoiceUrl": voice_url, - "VoiceMethod": voice_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceFallbackMethod": voice_fallback_method, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "VoiceCallerIdLookup": serialize.boolean_to_string( - voice_caller_id_lookup - ), - "SmsUrl": sms_url, - "SmsMethod": sms_method, - "SmsFallbackUrl": sms_fallback_url, - "SmsFallbackMethod": sms_fallback_method, - "SmsStatusCallback": sms_status_callback, - "MessageStatusCallback": message_status_callback, - "FriendlyName": friendly_name, - "PublicApplicationConnectEnabled": serialize.boolean_to_string( - public_application_connect_enabled - ), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + friendly_name=friendly_name, + public_application_connect_enabled=public_application_connect_enabled, ) - - return ApplicationInstance( + instance = ApplicationInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -778,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, @@ -799,6 +1562,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -828,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( @@ -837,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, @@ -864,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, @@ -894,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: """ @@ -909,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: """ @@ -921,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 9359545cdb..b608e9f141 100644 --- a/twilio/rest/api/v2010/account/authorized_connect_app.py +++ b/twilio/rest/api/v2010/account/authorized_connect_app.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( "account_sid": account_sid, "connect_app_sid": connect_app_sid or self.connect_app_sid, } + self._context: Optional[AuthorizedConnectAppContext] = None @property @@ -106,6 +108,24 @@ async def fetch_async(self) -> "AuthorizedConnectAppInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthorizedConnectAppInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -137,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 @@ -144,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: """ @@ -164,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: """ @@ -195,6 +269,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AuthorizedConnectAppInstance: :param payload: Payload response from the API """ + return AuthorizedConnectAppInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -278,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, @@ -297,6 +422,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -323,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( @@ -331,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, @@ -355,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, @@ -382,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 ) - return AuthorizedConnectAppPage(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 AuthorizedConnectAppPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AuthorizedConnectAppPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AuthorizedConnectAppPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AuthorizedConnectAppPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AuthorizedConnectAppPage: """ @@ -397,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: """ @@ -409,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 14fcfc28df..4b8207514d 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/__init__.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def __init__( "account_sid": account_sid, "country_code": country_code or self.country_code, } + self._context: Optional[AvailablePhoneNumberCountryContext] = None @property @@ -104,6 +106,24 @@ async def fetch_async(self) -> "AvailablePhoneNumberCountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailablePhoneNumberCountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailablePhoneNumberCountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def local(self) -> LocalList: """ @@ -196,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 @@ -203,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: """ @@ -223,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: @@ -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"] ) @@ -432,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, @@ -451,6 +576,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -477,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( @@ -485,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, @@ -509,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, @@ -536,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 ) - return AvailablePhoneNumberCountryPage(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 AvailablePhoneNumberCountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AvailablePhoneNumberCountryPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AvailablePhoneNumberCountryPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AvailablePhoneNumberCountryPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AvailablePhoneNumberCountryPage: """ @@ -551,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: """ @@ -563,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 43118d9f72..dd014b8221 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/local.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/local.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> LocalInstance: :param payload: Payload response from the API """ + return LocalInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams LocalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams LocalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists LocalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists LocalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -529,8 +851,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, @@ -561,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`. @@ -616,10 +944,204 @@ async def page_async( } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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: """ @@ -631,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: """ @@ -643,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 ee94aa944e..8413389849 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MachineToMachineInstance: :param payload: Payload response from the API """ + return MachineToMachineInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MachineToMachineInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MachineToMachineInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MachineToMachineInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MachineToMachineInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -529,8 +851,14 @@ def page( } ) - 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, @@ -561,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`. @@ -616,10 +944,204 @@ async def page_async( } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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: """ @@ -631,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: """ @@ -643,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 622d2b8597..393c3433a5 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/mobile.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/mobile.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MobileInstance: :param payload: Payload response from the API """ + return MobileInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MobileInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MobileInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MobileInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MobileInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -529,8 +851,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, @@ -561,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`. @@ -616,10 +944,204 @@ async def page_async( } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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: """ @@ -631,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: """ @@ -643,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 d0f3a63dda..1f1bf33a76 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/national.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/national.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> NationalInstance: :param payload: Payload response from the API """ + return NationalInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams NationalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams NationalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists NationalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists NationalInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -529,8 +851,14 @@ def page( } ) - 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, @@ -561,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`. @@ -616,10 +944,204 @@ async def page_async( } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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: """ @@ -631,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: """ @@ -643,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 7b5b9b11c8..fa9e3332c8 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SharedCostInstance: :param payload: Payload response from the API """ + return SharedCostInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SharedCostInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SharedCostInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SharedCostInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SharedCostInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -529,8 +851,14 @@ def page( } ) - 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, @@ -561,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`. @@ -616,10 +944,204 @@ async def page_async( } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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: """ @@ -631,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: """ @@ -643,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 4368018001..de41071b08 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TollFreeInstance: :param payload: Payload response from the API """ + return TollFreeInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TollFreeInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TollFreeInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TollFreeInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TollFreeInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -529,8 +851,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, @@ -561,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`. @@ -616,10 +944,204 @@ async def page_async( } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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: """ @@ -631,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: """ @@ -643,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 e0615d5a6e..0c319a53df 100644 --- a/twilio/rest/api/v2010/account/available_phone_number_country/voip.py +++ b/twilio/rest/api/v2010/account/available_phone_number_country/voip.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> VoipInstance: :param payload: Payload response from the API """ + return VoipInstance( self._version, payload, @@ -152,7 +154,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -233,7 +235,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -284,6 +286,166 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams VoipInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams VoipInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, area_code: Union[int, object] = values.unset, @@ -313,7 +475,7 @@ def list( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -339,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( area_code=area_code, @@ -393,7 +556,7 @@ async def list_async( memory before returning. :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -419,6 +582,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -445,6 +609,164 @@ async def list_async( ) ] + def list_with_http_info( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists VoipInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists VoipInstance and returns headers from first page + + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, area_code: Union[int, object] = values.unset, @@ -474,7 +796,7 @@ def page( Request is executed immediately :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. - :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param contains: Matching pattern to identify phone numbers. This pattern can be between 2 and 16 characters long and allows all digits (0-9) and all non-diacritic latin alphabet letters (a-z, A-Z). It accepts four meta-characters: `*`, `%`, `+`, `$`. The `*` and `%` meta-characters can appear multiple times in the pattern. To match wildcards at the beginning or end of the pattern, use `*` to match any single character or `%` to match a sequence of characters. If you use the wildcard patterns, it must include at least two non-meta-characters, and wildcards cannot be used between non-meta-characters. To match the beginning of a pattern, start the pattern with `+`. To match the end of the pattern, append the pattern with `$`. These meta-characters can't be adjacent to each other. :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. @@ -529,8 +851,14 @@ def page( } ) - 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, @@ -561,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`. @@ -616,10 +944,204 @@ async def page_async( } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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: """ @@ -631,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: """ @@ -643,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 97c7b33035..106e76e33d 100644 --- a/twilio/rest/api/v2010/account/balance.py +++ b/twilio/rest/api/v2010/account/balance.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,38 +67,86 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Balance.json".format(**self._solution) - def fetch(self) -> BalanceInstance: + def _fetch(self) -> tuple: """ - Asynchronously fetch the BalanceInstance - + Internal helper for fetch operation - :returns: The fetched BalanceInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> BalanceInstance: + """ + Fetch the BalanceInstance + + :returns: The fetched BalanceInstance + """ + payload, _, _ = self._fetch() return BalanceInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def fetch_async(self) -> BalanceInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronously fetch the BalanceInstance + Fetch the BalanceInstance and return response metadata - :returns: The fetched BalanceInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = BalanceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.fetch_async( + headers["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._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 ff9e98b09f..23b0121ee4 100644 --- a/twilio/rest/api/v2010/account/call/__init__.py +++ b/twilio/rest/api/v2010/account/call/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -130,6 +131,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[CallContext] = None @property @@ -166,6 +168,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CallInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CallInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CallInstance": """ Fetch the CallInstance @@ -184,6 +204,24 @@ async def fetch_async(self) -> "CallInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CallInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CallInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, url: Union[str, object] = values.unset, @@ -262,6 +300,84 @@ async def update_async( time_limit=time_limit, ) + def update_with_http_info( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the CallInstance with HTTP info + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + + async def update_with_http_info_async( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CallInstance with HTTP info + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + @property def events(self) -> EventList: """ @@ -366,6 +482,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): UserDefinedMessageSubscriptionList ] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CallInstance @@ -373,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({}) - 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, + 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,30 +809,117 @@ 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 - def events(self) -> EventList: - """ - Access the events - """ - if self._events is None: - self._events = EventList( - self._version, - self._solution["account_sid"], - self._solution["sid"], + async def update_async( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> CallInstance: + """ + Asynchronous coroutine to update the CallInstance + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: The updated CallInstance + """ + payload, _, _ = await self._update_async( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CallInstance and return response metadata + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + instance = CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def events(self) -> EventList: + """ + Access the events + """ + if self._events is None: + self._events = EventList( + self._version, + self._solution["account_sid"], + self._solution["sid"], ) return self._events @@ -675,6 +1047,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CallInstance: :param payload: Payload response from the API """ + return CallInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -706,7 +1079,7 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Calls.json".format(**self._solution) - def create( + def _create( self, to: str, from_: str, @@ -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,50 +1114,16 @@ 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( @@ -804,6 +1144,7 @@ def create( "RecordingChannels": recording_channels, "RecordingStatusCallback": recording_status_callback, "RecordingStatusCallbackMethod": recording_status_callback_method, + "RecordingConfigurationId": recording_configuration_id, "SipAuthUsername": sip_auth_username, "SipAuthPassword": sip_auth_password, "MachineDetection": machine_detection, @@ -824,6 +1165,7 @@ def create( "CallToken": call_token, "RecordingTrack": recording_track, "TimeLimit": time_limit, + "ClientNotificationUrl": client_notification_url, "Url": url, "Twiml": twiml, "ApplicationSid": application_sid, @@ -831,15 +1173,15 @@ def create( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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,97 +1257,626 @@ 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": serialize.boolean_to_string(record), - "RecordingChannels": recording_channels, - "RecordingStatusCallback": recording_status_callback, - "RecordingStatusCallbackMethod": recording_status_callback_method, - "SipAuthUsername": sip_auth_username, - "SipAuthPassword": sip_auth_password, - "MachineDetection": machine_detection, - "MachineDetectionTimeout": machine_detection_timeout, - "RecordingStatusCallbackEvent": serialize.map( - recording_status_callback_event, lambda e: e - ), - "Trim": trim, - "CallerId": caller_id, - "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, - "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, - "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, - "AsyncAmd": async_amd, - "AsyncAmdStatusCallback": async_amd_status_callback, - "AsyncAmdStatusCallbackMethod": async_amd_status_callback_method, - "Byoc": byoc, - "CallReason": call_reason, - "CallToken": call_token, - "RecordingTrack": recording_track, - "TimeLimit": time_limit, - "Url": url, - "Twiml": twiml, - "ApplicationSid": application_sid, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._create( + to=to, + from_=from_, + method=method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_event=status_callback_event, + status_callback_method=status_callback_method, + send_digits=send_digits, + timeout=timeout, + record=record, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_configuration_id=recording_configuration_id, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + machine_detection=machine_detection, + machine_detection_timeout=machine_detection_timeout, + recording_status_callback_event=recording_status_callback_event, + trim=trim, + caller_id=caller_id, + machine_detection_speech_threshold=machine_detection_speech_threshold, + machine_detection_speech_end_threshold=machine_detection_speech_end_threshold, + machine_detection_silence_timeout=machine_detection_silence_timeout, + async_amd=async_amd, + async_amd_status_callback=async_amd_status_callback, + async_amd_status_callback_method=async_amd_status_callback_method, + 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. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Create the CallInstance and return response metadata - :param 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 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. + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. :param str parent_call_sid: Only include calls spawned by calls with this SID. :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. - :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -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 UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -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 UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -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 UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param datetime start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param datetime start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param datetime end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param datetime end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -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 UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -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 UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. - :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. - :param end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. + :param start_time_before: Only include calls that started before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started before this date. + :param start_time_after: Only include calls that started on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on or after this date. + :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. + :param end_time_before: Only include calls that ended before this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended before this date. + :param end_time_after: Only include calls that ended on or after this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on or after this date. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -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,7 +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) + 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 7993dd00a0..96f3eae3bf 100644 --- a/twilio/rest/api/v2010/account/call/event.py +++ b/twilio/rest/api/v2010/account/call/event.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,6 +59,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EventInstance: :param payload: Payload response from the API """ + return EventInstance( self._version, payload, @@ -146,6 +148,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams EventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams EventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -165,6 +217,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -191,6 +244,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -199,6 +253,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists EventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists EventInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -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/notification.py b/twilio/rest/api/v2010/account/call/notification.py index 44291b8448..bed0f202c0 100644 --- a/twilio/rest/api/v2010/account/call/notification.py +++ b/twilio/rest/api/v2010/account/call/notification.py @@ -15,6 +15,7 @@ from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -82,6 +83,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[NotificationContext] = None @property @@ -119,6 +121,24 @@ async def fetch_async(self) -> "NotificationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -154,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 @@ -161,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: """ @@ -182,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: """ @@ -214,6 +290,7 @@ def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: :param payload: Payload response from the API """ + return NotificationInstance( self._version, payload, @@ -332,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, @@ -359,6 +512,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( log=log, @@ -397,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( @@ -409,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, @@ -445,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, @@ -484,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: """ @@ -499,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: """ @@ -511,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 00f76be814..1d203e8521 100644 --- a/twilio/rest/api/v2010/account/call/payment.py +++ b/twilio/rest/api/v2010/account/call/payment.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -35,6 +36,10 @@ class Capture(object): POSTAL_CODE = "postal-code" BANK_ROUTING_NUMBER = "bank-routing-number" BANK_ACCOUNT_NUMBER = "bank-account-number" + PAYMENT_CARD_NUMBER_MATCHER = "payment-card-number-matcher" + EXPIRATION_DATE_MATCHER = "expiration-date-matcher" + SECURITY_CODE_MATCHER = "security-code-matcher" + POSTAL_CODE_MATCHER = "postal-code-matcher" class PaymentMethod(object): CREDIT_CARD = "credit-card" @@ -84,6 +89,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[PaymentContext] = None @property @@ -151,6 +157,54 @@ async def update_async( status=status, ) + def update_with_http_info( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Update the PaymentInstance with HTTP info + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) + + async def update_with_http_info_async( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PaymentInstance with HTTP info + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -186,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, @@ -211,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, @@ -226,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, @@ -251,13 +357,39 @@ 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, + 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, @@ -266,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 @@ -298,7 +462,7 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): **self._solution ) - def create( + def _create( self, idempotency_key: str, status_callback: str, @@ -318,28 +482,14 @@ def create( timeout: Union[int, object] = values.unset, token_type: Union["PaymentInstance.TokenType", object] = values.unset, valid_card_types: Union[str, object] = values.unset, - ) -> PaymentInstance: + require_matching_inputs: Union[str, object] = values.unset, + confirmation: Union[str, object] = values.unset, + ) -> tuple: """ - Create the PaymentInstance + Internal helper for create operation - :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. - :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [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` - - :returns: The created PaymentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -360,14 +510,87 @@ def create( "Timeout": timeout, "TokenType": token_type, "ValidCardTypes": valid_card_types, + "RequireMatchingInputs": require_matching_inputs, + "Confirmation": confirmation, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, + idempotency_key: str, + status_callback: str, + bank_account_type: Union[ + "PaymentInstance.BankAccountType", object + ] = values.unset, + charge_amount: Union[float, object] = values.unset, + currency: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + input: Union[str, object] = values.unset, + min_postal_code_length: Union[int, object] = values.unset, + parameter: Union[object, object] = values.unset, + payment_connector: Union[str, object] = values.unset, + payment_method: Union["PaymentInstance.PaymentMethod", object] = values.unset, + postal_code: Union[bool, object] = values.unset, + security_code: Union[bool, object] = values.unset, + timeout: Union[int, object] = values.unset, + token_type: Union["PaymentInstance.TokenType", object] = values.unset, + valid_card_types: Union[str, object] = values.unset, + require_matching_inputs: Union[str, object] = values.unset, + confirmation: Union[str, object] = values.unset, + ) -> PaymentInstance: + """ + Create the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [expected StatusCallback values](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback) + :param bank_account_type: + :param charge_amount: A positive decimal value less than 1,000,000 to charge against the credit card or bank account. Default currency can be overwritten with `currency` field. Leave blank or set to 0 to tokenize. + :param currency: The currency of the `charge_amount`, formatted as [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format. The default value is `USD` and all values allowed from the Pay Connector are accepted. + :param description: The description can be used to provide more details regarding the transaction. This information is submitted along with the payment details to the Payment Connector which are then posted on the transactions. + :param input: A list of inputs that should be accepted. Currently only `dtmf` is supported. All digits captured during a pay session are redacted from the logs. + :param min_postal_code_length: A positive integer that is used to validate the length of the `PostalCode` inputted by the user. User must enter this many digits. + :param parameter: A single-level JSON object used to pass custom parameters to payment processors. (Required for ACH payments). The information that has to be included here depends on the Connector. [Read more](https://www.twilio.com/console/voice/pay-connectors). + :param payment_connector: This is the unique name corresponding to the Pay Connector installed in the Twilio Add-ons. Learn more about [ Connectors](https://www.twilio.com/console/voice/pay-connectors). The default value is `Default`. + :param payment_method: + :param postal_code: Indicates whether the credit card postal code (zip code) is a required piece of payment information that must be provided by the caller. The default is `true`. + :param security_code: Indicates whether the credit card security code is a required piece of payment information that must be provided by the caller. The default is `true`. + :param timeout: The number of seconds that should wait for the caller to press a digit between each subsequent digit, after the first one, before moving on to validate the digits captured. The default is `5`, maximum is `600`. + :param token_type: + :param valid_card_types: Credit card types separated by space that Pay should accept. The default value is `visa mastercard amex` + :param require_matching_inputs: A comma-separated list of payment information fields that require the caller to enter the same value twice for confirmation. Supported values are `payment-card-number`, `expiration-date`, `security-code`, and `postal-code`. + :param confirmation: Whether to prompt the caller to confirm their payment information before submitting to the payment gateway. If `true`, the caller will hear the last 4 digits of their card or account number and must press 1 to confirm or 2 to cancel. Default is `false`. + + :returns: The created PaymentInstance + """ + payload, _, _ = self._create( + idempotency_key=idempotency_key, + status_callback=status_callback, + bank_account_type=bank_account_type, + charge_amount=charge_amount, + currency=currency, + description=description, + input=input, + min_postal_code_length=min_postal_code_length, + parameter=parameter, + payment_connector=payment_connector, + payment_method=payment_method, + postal_code=postal_code, + security_code=security_code, + timeout=timeout, + token_type=token_type, + valid_card_types=valid_card_types, + require_matching_inputs=require_matching_inputs, + confirmation=confirmation, + ) return PaymentInstance( self._version, payload, @@ -375,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, @@ -395,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) @@ -415,8 +640,67 @@ async def create_async( :param timeout: The number of seconds that should wait for the caller to press a digit between each subsequent digit, after the first one, before moving on to validate the digits captured. The default is `5`, maximum is `600`. :param token_type: :param valid_card_types: Credit card types separated by space that Pay should accept. The default value is `visa mastercard amex` + :param require_matching_inputs: A comma-separated list of payment information fields that require the caller to enter the same value twice for confirmation. Supported values are `payment-card-number`, `expiration-date`, `security-code`, and `postal-code`. + :param confirmation: Whether to prompt the caller to confirm their payment information before submitting to the payment gateway. If `true`, the caller will hear the last 4 digits of their card or account number and must press 1 to confirm or 2 to cancel. Default is `false`. - :returns: The created PaymentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + idempotency_key=idempotency_key, + status_callback=status_callback, + bank_account_type=bank_account_type, + charge_amount=charge_amount, + currency=currency, + description=description, + input=input, + min_postal_code_length=min_postal_code_length, + parameter=parameter, + payment_connector=payment_connector, + payment_method=payment_method, + postal_code=postal_code, + security_code=security_code, + timeout=timeout, + token_type=token_type, + valid_card_types=valid_card_types, + require_matching_inputs=require_matching_inputs, + confirmation=confirmation, + ) + instance = PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + idempotency_key: str, + status_callback: str, + bank_account_type: Union[ + "PaymentInstance.BankAccountType", object + ] = values.unset, + charge_amount: Union[float, object] = values.unset, + currency: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + input: Union[str, object] = values.unset, + min_postal_code_length: Union[int, object] = values.unset, + parameter: Union[object, object] = values.unset, + payment_connector: Union[str, object] = values.unset, + payment_method: Union["PaymentInstance.PaymentMethod", object] = values.unset, + postal_code: Union[bool, object] = values.unset, + security_code: Union[bool, object] = values.unset, + timeout: Union[int, object] = values.unset, + token_type: Union["PaymentInstance.TokenType", object] = values.unset, + valid_card_types: Union[str, object] = values.unset, + require_matching_inputs: Union[str, object] = values.unset, + confirmation: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -437,14 +721,87 @@ async def create_async( "Timeout": timeout, "TokenType": token_type, "ValidCardTypes": valid_card_types, + "RequireMatchingInputs": require_matching_inputs, + "Confirmation": confirmation, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, + 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, @@ -452,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 71158a2fe8..1e17481856 100644 --- a/twilio/rest/api/v2010/account/call/recording.py +++ b/twilio/rest/api/v2010/account/call/recording.py @@ -15,6 +15,7 @@ from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -104,6 +105,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[RecordingContext] = None @property @@ -141,6 +143,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RecordingInstance": """ Fetch the RecordingInstance @@ -159,6 +179,24 @@ async def fetch_async(self) -> "RecordingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: "RecordingInstance.Status", @@ -195,6 +233,42 @@ async def update_async( pause_behavior=pause_behavior, ) + def update_with_http_info( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RecordingInstance with HTTP info + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + pause_behavior=pause_behavior, + ) + + async def update_with_http_info_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RecordingInstance with HTTP info + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + pause_behavior=pause_behavior, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -230,6 +304,20 @@ def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RecordingInstance @@ -237,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: @@ -249,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: @@ -261,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: """ @@ -282,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" - 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: "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, @@ -330,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({}) - 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, @@ -364,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 @@ -382,6 +640,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: :param payload: Payload response from the API """ + return RecordingInstance( self._version, payload, @@ -420,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, @@ -428,18 +687,13 @@ def create( trim: Union[str, object] = values.unset, recording_channels: Union[str, object] = values.unset, recording_track: Union[str, object] = values.unset, - ) -> RecordingInstance: + recording_configuration_id: Union[str, object] = values.unset, + ) -> tuple: """ - Create the RecordingInstance - - :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( @@ -452,14 +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"}) - 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, + 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, @@ -467,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, @@ -475,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). @@ -485,8 +777,42 @@ async def create_async( :param trim: Whether to trim any leading and trailing silence in the recording. Can be: `trim-silence` or `do-not-trim` and the default is `do-not-trim`. `trim-silence` trims the silence from the beginning and end of the recording and `do-not-trim` does not. :param recording_channels: The number of channels used in the recording. Can be: `mono` or `dual` and the default is `mono`. `mono` records all parties of the call into one channel. `dual` records each party of a 2-party call into separate channels. :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + recording_status_callback_event=recording_status_callback_event, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + trim=trim, + recording_channels=recording_channels, + recording_track=recording_track, + recording_configuration_id=recording_configuration_id, + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: The created RecordingInstance + async def _create_async( + self, + recording_status_callback_event: Union[List[str], object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -499,14 +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"}) - 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, + 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, @@ -514,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, @@ -586,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, @@ -611,6 +1084,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -646,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( @@ -657,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, @@ -690,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, @@ -726,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: """ @@ -741,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: """ @@ -753,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 28a0734e19..30ffea6d94 100644 --- a/twilio/rest/api/v2010/account/call/siprec.py +++ b/twilio/rest/api/v2010/account/call/siprec.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[SiprecContext] = None @property @@ -115,6 +117,34 @@ async def update_async( status=status, ) + def update_with_http_info( + self, status: "SiprecInstance.UpdateStatus" + ) -> ApiResponse: + """ + Update the SiprecInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "SiprecInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SiprecInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -148,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 - - :param status: + Internal helper for update operation - :returns: The updated SiprecInstance + 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: "SiprecInstance.UpdateStatus") -> SiprecInstance: + """ + Update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + payload, _, _ = self._update(status=status) return SiprecInstance( self._version, payload, @@ -176,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, @@ -206,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 @@ -238,7 +332,2122 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): **self._solution ) - def create( + def _create( + self, + name: Union[str, object] = values.unset, + connector_name: Union[str, object] = values.unset, + track: Union["SiprecInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Name": name, + "ConnectorName": connector_name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + name: Union[str, object] = values.unset, + connector_name: Union[str, object] = values.unset, + track: Union["SiprecInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> SiprecInstance: + """ + Create the SiprecInstance + + :param name: The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. + :param connector_name: Unique name used when configuring the connector via Marketplace Add-on. + :param track: + :param status_callback: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: The created SiprecInstance + """ + payload, _, _ = self._create( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, + ) + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def create_with_http_info( + self, + name: Union[str, object] = values.unset, + connector_name: Union[str, object] = values.unset, + track: Union["SiprecInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the SiprecInstance and return response metadata + + :param name: The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. + :param connector_name: Unique name used when configuring the connector via Marketplace Add-on. + :param track: + :param status_callback: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, + ) + instance = SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + name: Union[str, object] = values.unset, + connector_name: Union[str, object] = values.unset, + track: Union["SiprecInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Name": name, + "ConnectorName": connector_name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( self, name: Union[str, object] = values.unset, connector_name: Union[str, object] = values.unset, @@ -445,7 +2654,7 @@ def create( parameter99_value: Union[str, object] = values.unset, ) -> SiprecInstance: """ - Create the SiprecInstance + Asynchronously create the SiprecInstance :param name: The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. :param connector_name: Unique name used when configuring the connector via Marketplace Add-on. @@ -615,258 +2824,249 @@ def create( :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 - """ - - 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"}) + :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, headers=headers + :returns: The created SiprecInstance + """ + payload, _, _ = await self._create_async( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, ) - return SiprecInstance( self._version, payload, @@ -874,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, @@ -1079,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. @@ -1287,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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, ) - - return SiprecInstance( + instance = SiprecInstance( self._version, payload, account_sid=self._solution["account_sid"], call_sid=self._solution["call_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def get(self, sid: str) -> SiprecContext: """ diff --git a/twilio/rest/api/v2010/account/call/stream.py b/twilio/rest/api/v2010/account/call/stream.py index b3fa197bf8..99338e0663 100644 --- a/twilio/rest/api/v2010/account/call/stream.py +++ b/twilio/rest/api/v2010/account/call/stream.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[StreamContext] = None @property @@ -115,6 +117,34 @@ async def update_async( status=status, ) + def update_with_http_info( + self, status: "StreamInstance.UpdateStatus" + ) -> ApiResponse: + """ + Update the StreamInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "StreamInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the StreamInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -150,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 - - :param status: + Internal helper for update operation - :returns: The updated StreamInstance + 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: "StreamInstance.UpdateStatus") -> StreamInstance: + """ + Update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + payload, _, _ = self._update(status=status) return StreamInstance( self._version, payload, @@ -178,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, @@ -208,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 @@ -240,7 +334,2122 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): **self._solution ) - def create( + def _create( + self, + url: str, + name: Union[str, object] = values.unset, + track: Union["StreamInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Url": url, + "Name": name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + url: str, + name: Union[str, object] = values.unset, + track: Union["StreamInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> StreamInstance: + """ + Create the StreamInstance + + :param url: Relative or absolute URL where WebSocket connection will be established. + :param name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. + :param track: + :param status_callback: Absolute URL to which Twilio sends status callback HTTP requests. + :param status_callback_method: The HTTP method Twilio uses when sending `status_callback` requests. Possible values are `GET` and `POST`. Default is `POST`. + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: The created StreamInstance + """ + payload, _, _ = self._create( + url=url, + name=name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, + ) + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def create_with_http_info( + self, + url: str, + name: Union[str, object] = values.unset, + track: Union["StreamInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the StreamInstance and return response metadata + + :param url: Relative or absolute URL where WebSocket connection will be established. + :param name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. + :param track: + :param status_callback: Absolute URL to which Twilio sends status callback HTTP requests. + :param status_callback_method: The HTTP method Twilio uses when sending `status_callback` requests. Possible values are `GET` and `POST`. Default is `POST`. + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + url=url, + name=name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, + ) + instance = StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + url: str, + name: Union[str, object] = values.unset, + track: Union["StreamInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Url": url, + "Name": name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( self, url: str, name: Union[str, object] = values.unset, @@ -447,7 +2656,7 @@ def create( parameter99_value: Union[str, object] = values.unset, ) -> StreamInstance: """ - Create the StreamInstance + Asynchronously create the StreamInstance :param url: Relative or absolute URL where WebSocket connection will be established. :param name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. @@ -617,258 +2826,249 @@ def create( :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 - """ - - 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"}) + :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, headers=headers + :returns: The created StreamInstance + """ + payload, _, _ = await self._create_async( + url=url, + name=name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, ) - return StreamInstance( self._version, payload, @@ -876,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, @@ -1081,9 +3281,9 @@ async def create_async( parameter98_value: Union[str, object] = values.unset, parameter99_name: Union[str, object] = values.unset, parameter99_value: Union[str, object] = values.unset, - ) -> StreamInstance: + ) -> ApiResponse: """ - Asynchronously create the StreamInstance + Asynchronously create the StreamInstance and return response metadata :param url: Relative or absolute URL where WebSocket connection will be established. :param name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. @@ -1289,228 +3489,220 @@ async def create_async( :param parameter99_name: Parameter name :param parameter99_value: Parameter value - :returns: The created StreamInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "Url": url, - "Name": name, - "Track": track, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "Parameter1.Name": parameter1_name, - "Parameter1.Value": parameter1_value, - "Parameter2.Name": parameter2_name, - "Parameter2.Value": parameter2_value, - "Parameter3.Name": parameter3_name, - "Parameter3.Value": parameter3_value, - "Parameter4.Name": parameter4_name, - "Parameter4.Value": parameter4_value, - "Parameter5.Name": parameter5_name, - "Parameter5.Value": parameter5_value, - "Parameter6.Name": parameter6_name, - "Parameter6.Value": parameter6_value, - "Parameter7.Name": parameter7_name, - "Parameter7.Value": parameter7_value, - "Parameter8.Name": parameter8_name, - "Parameter8.Value": parameter8_value, - "Parameter9.Name": parameter9_name, - "Parameter9.Value": parameter9_value, - "Parameter10.Name": parameter10_name, - "Parameter10.Value": parameter10_value, - "Parameter11.Name": parameter11_name, - "Parameter11.Value": parameter11_value, - "Parameter12.Name": parameter12_name, - "Parameter12.Value": parameter12_value, - "Parameter13.Name": parameter13_name, - "Parameter13.Value": parameter13_value, - "Parameter14.Name": parameter14_name, - "Parameter14.Value": parameter14_value, - "Parameter15.Name": parameter15_name, - "Parameter15.Value": parameter15_value, - "Parameter16.Name": parameter16_name, - "Parameter16.Value": parameter16_value, - "Parameter17.Name": parameter17_name, - "Parameter17.Value": parameter17_value, - "Parameter18.Name": parameter18_name, - "Parameter18.Value": parameter18_value, - "Parameter19.Name": parameter19_name, - "Parameter19.Value": parameter19_value, - "Parameter20.Name": parameter20_name, - "Parameter20.Value": parameter20_value, - "Parameter21.Name": parameter21_name, - "Parameter21.Value": parameter21_value, - "Parameter22.Name": parameter22_name, - "Parameter22.Value": parameter22_value, - "Parameter23.Name": parameter23_name, - "Parameter23.Value": parameter23_value, - "Parameter24.Name": parameter24_name, - "Parameter24.Value": parameter24_value, - "Parameter25.Name": parameter25_name, - "Parameter25.Value": parameter25_value, - "Parameter26.Name": parameter26_name, - "Parameter26.Value": parameter26_value, - "Parameter27.Name": parameter27_name, - "Parameter27.Value": parameter27_value, - "Parameter28.Name": parameter28_name, - "Parameter28.Value": parameter28_value, - "Parameter29.Name": parameter29_name, - "Parameter29.Value": parameter29_value, - "Parameter30.Name": parameter30_name, - "Parameter30.Value": parameter30_value, - "Parameter31.Name": parameter31_name, - "Parameter31.Value": parameter31_value, - "Parameter32.Name": parameter32_name, - "Parameter32.Value": parameter32_value, - "Parameter33.Name": parameter33_name, - "Parameter33.Value": parameter33_value, - "Parameter34.Name": parameter34_name, - "Parameter34.Value": parameter34_value, - "Parameter35.Name": parameter35_name, - "Parameter35.Value": parameter35_value, - "Parameter36.Name": parameter36_name, - "Parameter36.Value": parameter36_value, - "Parameter37.Name": parameter37_name, - "Parameter37.Value": parameter37_value, - "Parameter38.Name": parameter38_name, - "Parameter38.Value": parameter38_value, - "Parameter39.Name": parameter39_name, - "Parameter39.Value": parameter39_value, - "Parameter40.Name": parameter40_name, - "Parameter40.Value": parameter40_value, - "Parameter41.Name": parameter41_name, - "Parameter41.Value": parameter41_value, - "Parameter42.Name": parameter42_name, - "Parameter42.Value": parameter42_value, - "Parameter43.Name": parameter43_name, - "Parameter43.Value": parameter43_value, - "Parameter44.Name": parameter44_name, - "Parameter44.Value": parameter44_value, - "Parameter45.Name": parameter45_name, - "Parameter45.Value": parameter45_value, - "Parameter46.Name": parameter46_name, - "Parameter46.Value": parameter46_value, - "Parameter47.Name": parameter47_name, - "Parameter47.Value": parameter47_value, - "Parameter48.Name": parameter48_name, - "Parameter48.Value": parameter48_value, - "Parameter49.Name": parameter49_name, - "Parameter49.Value": parameter49_value, - "Parameter50.Name": parameter50_name, - "Parameter50.Value": parameter50_value, - "Parameter51.Name": parameter51_name, - "Parameter51.Value": parameter51_value, - "Parameter52.Name": parameter52_name, - "Parameter52.Value": parameter52_value, - "Parameter53.Name": parameter53_name, - "Parameter53.Value": parameter53_value, - "Parameter54.Name": parameter54_name, - "Parameter54.Value": parameter54_value, - "Parameter55.Name": parameter55_name, - "Parameter55.Value": parameter55_value, - "Parameter56.Name": parameter56_name, - "Parameter56.Value": parameter56_value, - "Parameter57.Name": parameter57_name, - "Parameter57.Value": parameter57_value, - "Parameter58.Name": parameter58_name, - "Parameter58.Value": parameter58_value, - "Parameter59.Name": parameter59_name, - "Parameter59.Value": parameter59_value, - "Parameter60.Name": parameter60_name, - "Parameter60.Value": parameter60_value, - "Parameter61.Name": parameter61_name, - "Parameter61.Value": parameter61_value, - "Parameter62.Name": parameter62_name, - "Parameter62.Value": parameter62_value, - "Parameter63.Name": parameter63_name, - "Parameter63.Value": parameter63_value, - "Parameter64.Name": parameter64_name, - "Parameter64.Value": parameter64_value, - "Parameter65.Name": parameter65_name, - "Parameter65.Value": parameter65_value, - "Parameter66.Name": parameter66_name, - "Parameter66.Value": parameter66_value, - "Parameter67.Name": parameter67_name, - "Parameter67.Value": parameter67_value, - "Parameter68.Name": parameter68_name, - "Parameter68.Value": parameter68_value, - "Parameter69.Name": parameter69_name, - "Parameter69.Value": parameter69_value, - "Parameter70.Name": parameter70_name, - "Parameter70.Value": parameter70_value, - "Parameter71.Name": parameter71_name, - "Parameter71.Value": parameter71_value, - "Parameter72.Name": parameter72_name, - "Parameter72.Value": parameter72_value, - "Parameter73.Name": parameter73_name, - "Parameter73.Value": parameter73_value, - "Parameter74.Name": parameter74_name, - "Parameter74.Value": parameter74_value, - "Parameter75.Name": parameter75_name, - "Parameter75.Value": parameter75_value, - "Parameter76.Name": parameter76_name, - "Parameter76.Value": parameter76_value, - "Parameter77.Name": parameter77_name, - "Parameter77.Value": parameter77_value, - "Parameter78.Name": parameter78_name, - "Parameter78.Value": parameter78_value, - "Parameter79.Name": parameter79_name, - "Parameter79.Value": parameter79_value, - "Parameter80.Name": parameter80_name, - "Parameter80.Value": parameter80_value, - "Parameter81.Name": parameter81_name, - "Parameter81.Value": parameter81_value, - "Parameter82.Name": parameter82_name, - "Parameter82.Value": parameter82_value, - "Parameter83.Name": parameter83_name, - "Parameter83.Value": parameter83_value, - "Parameter84.Name": parameter84_name, - "Parameter84.Value": parameter84_value, - "Parameter85.Name": parameter85_name, - "Parameter85.Value": parameter85_value, - "Parameter86.Name": parameter86_name, - "Parameter86.Value": parameter86_value, - "Parameter87.Name": parameter87_name, - "Parameter87.Value": parameter87_value, - "Parameter88.Name": parameter88_name, - "Parameter88.Value": parameter88_value, - "Parameter89.Name": parameter89_name, - "Parameter89.Value": parameter89_value, - "Parameter90.Name": parameter90_name, - "Parameter90.Value": parameter90_value, - "Parameter91.Name": parameter91_name, - "Parameter91.Value": parameter91_value, - "Parameter92.Name": parameter92_name, - "Parameter92.Value": parameter92_value, - "Parameter93.Name": parameter93_name, - "Parameter93.Value": parameter93_value, - "Parameter94.Name": parameter94_name, - "Parameter94.Value": parameter94_value, - "Parameter95.Name": parameter95_name, - "Parameter95.Value": parameter95_value, - "Parameter96.Name": parameter96_name, - "Parameter96.Value": parameter96_value, - "Parameter97.Name": parameter97_name, - "Parameter97.Value": parameter97_value, - "Parameter98.Name": parameter98_name, - "Parameter98.Value": parameter98_value, - "Parameter99.Name": parameter99_name, - "Parameter99.Value": parameter99_value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + url=url, + name=name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + parameter1_name=parameter1_name, + parameter1_value=parameter1_value, + parameter2_name=parameter2_name, + parameter2_value=parameter2_value, + parameter3_name=parameter3_name, + parameter3_value=parameter3_value, + parameter4_name=parameter4_name, + parameter4_value=parameter4_value, + parameter5_name=parameter5_name, + parameter5_value=parameter5_value, + parameter6_name=parameter6_name, + parameter6_value=parameter6_value, + parameter7_name=parameter7_name, + parameter7_value=parameter7_value, + parameter8_name=parameter8_name, + parameter8_value=parameter8_value, + parameter9_name=parameter9_name, + parameter9_value=parameter9_value, + parameter10_name=parameter10_name, + parameter10_value=parameter10_value, + parameter11_name=parameter11_name, + parameter11_value=parameter11_value, + parameter12_name=parameter12_name, + parameter12_value=parameter12_value, + parameter13_name=parameter13_name, + parameter13_value=parameter13_value, + parameter14_name=parameter14_name, + parameter14_value=parameter14_value, + parameter15_name=parameter15_name, + parameter15_value=parameter15_value, + parameter16_name=parameter16_name, + parameter16_value=parameter16_value, + parameter17_name=parameter17_name, + parameter17_value=parameter17_value, + parameter18_name=parameter18_name, + parameter18_value=parameter18_value, + parameter19_name=parameter19_name, + parameter19_value=parameter19_value, + parameter20_name=parameter20_name, + parameter20_value=parameter20_value, + parameter21_name=parameter21_name, + parameter21_value=parameter21_value, + parameter22_name=parameter22_name, + parameter22_value=parameter22_value, + parameter23_name=parameter23_name, + parameter23_value=parameter23_value, + parameter24_name=parameter24_name, + parameter24_value=parameter24_value, + parameter25_name=parameter25_name, + parameter25_value=parameter25_value, + parameter26_name=parameter26_name, + parameter26_value=parameter26_value, + parameter27_name=parameter27_name, + parameter27_value=parameter27_value, + parameter28_name=parameter28_name, + parameter28_value=parameter28_value, + parameter29_name=parameter29_name, + parameter29_value=parameter29_value, + parameter30_name=parameter30_name, + parameter30_value=parameter30_value, + parameter31_name=parameter31_name, + parameter31_value=parameter31_value, + parameter32_name=parameter32_name, + parameter32_value=parameter32_value, + parameter33_name=parameter33_name, + parameter33_value=parameter33_value, + parameter34_name=parameter34_name, + parameter34_value=parameter34_value, + parameter35_name=parameter35_name, + parameter35_value=parameter35_value, + parameter36_name=parameter36_name, + parameter36_value=parameter36_value, + parameter37_name=parameter37_name, + parameter37_value=parameter37_value, + parameter38_name=parameter38_name, + parameter38_value=parameter38_value, + parameter39_name=parameter39_name, + parameter39_value=parameter39_value, + parameter40_name=parameter40_name, + parameter40_value=parameter40_value, + parameter41_name=parameter41_name, + parameter41_value=parameter41_value, + parameter42_name=parameter42_name, + parameter42_value=parameter42_value, + parameter43_name=parameter43_name, + parameter43_value=parameter43_value, + parameter44_name=parameter44_name, + parameter44_value=parameter44_value, + parameter45_name=parameter45_name, + parameter45_value=parameter45_value, + parameter46_name=parameter46_name, + parameter46_value=parameter46_value, + parameter47_name=parameter47_name, + parameter47_value=parameter47_value, + parameter48_name=parameter48_name, + parameter48_value=parameter48_value, + parameter49_name=parameter49_name, + parameter49_value=parameter49_value, + parameter50_name=parameter50_name, + parameter50_value=parameter50_value, + parameter51_name=parameter51_name, + parameter51_value=parameter51_value, + parameter52_name=parameter52_name, + parameter52_value=parameter52_value, + parameter53_name=parameter53_name, + parameter53_value=parameter53_value, + parameter54_name=parameter54_name, + parameter54_value=parameter54_value, + parameter55_name=parameter55_name, + parameter55_value=parameter55_value, + parameter56_name=parameter56_name, + parameter56_value=parameter56_value, + parameter57_name=parameter57_name, + parameter57_value=parameter57_value, + parameter58_name=parameter58_name, + parameter58_value=parameter58_value, + parameter59_name=parameter59_name, + parameter59_value=parameter59_value, + parameter60_name=parameter60_name, + parameter60_value=parameter60_value, + parameter61_name=parameter61_name, + parameter61_value=parameter61_value, + parameter62_name=parameter62_name, + parameter62_value=parameter62_value, + parameter63_name=parameter63_name, + parameter63_value=parameter63_value, + parameter64_name=parameter64_name, + parameter64_value=parameter64_value, + parameter65_name=parameter65_name, + parameter65_value=parameter65_value, + parameter66_name=parameter66_name, + parameter66_value=parameter66_value, + parameter67_name=parameter67_name, + parameter67_value=parameter67_value, + parameter68_name=parameter68_name, + parameter68_value=parameter68_value, + parameter69_name=parameter69_name, + parameter69_value=parameter69_value, + parameter70_name=parameter70_name, + parameter70_value=parameter70_value, + parameter71_name=parameter71_name, + parameter71_value=parameter71_value, + parameter72_name=parameter72_name, + parameter72_value=parameter72_value, + parameter73_name=parameter73_name, + parameter73_value=parameter73_value, + parameter74_name=parameter74_name, + parameter74_value=parameter74_value, + parameter75_name=parameter75_name, + parameter75_value=parameter75_value, + parameter76_name=parameter76_name, + parameter76_value=parameter76_value, + parameter77_name=parameter77_name, + parameter77_value=parameter77_value, + parameter78_name=parameter78_name, + parameter78_value=parameter78_value, + parameter79_name=parameter79_name, + parameter79_value=parameter79_value, + parameter80_name=parameter80_name, + parameter80_value=parameter80_value, + parameter81_name=parameter81_name, + parameter81_value=parameter81_value, + parameter82_name=parameter82_name, + parameter82_value=parameter82_value, + parameter83_name=parameter83_name, + parameter83_value=parameter83_value, + parameter84_name=parameter84_name, + parameter84_value=parameter84_value, + parameter85_name=parameter85_name, + parameter85_value=parameter85_value, + parameter86_name=parameter86_name, + parameter86_value=parameter86_value, + parameter87_name=parameter87_name, + parameter87_value=parameter87_value, + parameter88_name=parameter88_name, + parameter88_value=parameter88_value, + parameter89_name=parameter89_name, + parameter89_value=parameter89_value, + parameter90_name=parameter90_name, + parameter90_value=parameter90_value, + parameter91_name=parameter91_name, + parameter91_value=parameter91_value, + parameter92_name=parameter92_name, + parameter92_value=parameter92_value, + parameter93_name=parameter93_name, + parameter93_value=parameter93_value, + parameter94_name=parameter94_name, + parameter94_value=parameter94_value, + parameter95_name=parameter95_name, + parameter95_value=parameter95_value, + parameter96_name=parameter96_name, + parameter96_value=parameter96_value, + parameter97_name=parameter97_name, + parameter97_value=parameter97_value, + parameter98_name=parameter98_name, + parameter98_value=parameter98_value, + parameter99_name=parameter99_name, + parameter99_value=parameter99_value, ) - - return StreamInstance( + instance = StreamInstance( self._version, payload, account_sid=self._solution["account_sid"], call_sid=self._solution["call_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def get(self, sid: str) -> StreamContext: """ diff --git a/twilio/rest/api/v2010/account/call/transcription.py b/twilio/rest/api/v2010/account/call/transcription.py index 96554eaa02..0d56c61ff3 100644 --- a/twilio/rest/api/v2010/account/call/transcription.py +++ b/twilio/rest/api/v2010/account/call/transcription.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[TranscriptionContext] = None @property @@ -117,6 +119,34 @@ async def update_async( status=status, ) + def update_with_http_info( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> ApiResponse: + """ + Update the TranscriptionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TranscriptionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -152,28 +182,40 @@ def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): ) ) - def update( - self, status: "TranscriptionInstance.UpdateStatus" - ) -> TranscriptionInstance: + def _update(self, status: "TranscriptionInstance.UpdateStatus") -> tuple: """ - Update the TranscriptionInstance - - :param status: + Internal helper for update operation - :returns: The updated TranscriptionInstance + 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: "TranscriptionInstance.UpdateStatus" + ) -> TranscriptionInstance: + """ + Update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + payload, _, _ = self._update(status=status) return TranscriptionInstance( self._version, payload, @@ -182,28 +224,62 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, status: "TranscriptionInstance.UpdateStatus" - ) -> TranscriptionInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the TranscriptionInstance + Update the TranscriptionInstance and return response metadata :param status: - :returns: The updated TranscriptionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(status=status) + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> tuple: """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "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: "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, @@ -212,6 +288,26 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TranscriptionInstance and return response metadata + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(status=status) + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -246,7 +342,7 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): ) ) - def create( + def _create( self, name: Union[str, object] = values.unset, track: Union["TranscriptionInstance.Track", object] = values.unset, @@ -261,421 +357,17 @@ def create( speech_model: Union[str, object] = values.unset, hints: Union[str, object] = values.unset, enable_automatic_punctuation: Union[bool, 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, - ) -> TranscriptionInstance: + 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: """ - 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 send 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, between 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, between 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 adds punctuation to recognition result hypotheses - :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 + Internal helper for create operation - :returns: The created TranscriptionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -695,212 +387,88 @@ def create( "EnableAutomaticPunctuation": serialize.boolean_to_string( enable_automatic_punctuation ), - "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, + "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"}) - 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, + 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, @@ -908,7 +476,7 @@ def create( call_sid=self._solution["call_sid"], ) - async def create_async( + def create_with_http_info( self, name: Union[str, object] = values.unset, track: Union["TranscriptionInstance.Track", object] = values.unset, @@ -923,207 +491,14 @@ async def create_async( speech_model: Union[str, object] = values.unset, hints: Union[str, object] = values.unset, enable_automatic_punctuation: Union[bool, 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, - ) -> TranscriptionInstance: + 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 + 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: @@ -1131,213 +506,75 @@ async def create_async( :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 send to the customer + :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, between those supported by Twilio + :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, between those supported by the provider + :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 adds punctuation to recognition result hypotheses - :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 + :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) - :returns: The created TranscriptionInstance + 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( @@ -1357,212 +594,88 @@ async def create_async( "EnableAutomaticPunctuation": serialize.boolean_to_string( enable_automatic_punctuation ), - "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, + "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"}) - 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: 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, @@ -1570,6 +683,79 @@ async def create_async( call_sid=self._solution["call_sid"], ) + async def create_with_http_info_async( + self, + name: Union[str, object] = values.unset, + track: Union["TranscriptionInstance.Track", object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + inbound_track_label: Union[str, object] = values.unset, + outbound_track_label: Union[str, object] = values.unset, + partial_results: Union[bool, object] = values.unset, + language_code: Union[str, object] = values.unset, + transcription_engine: Union[str, object] = values.unset, + profanity_filter: Union[bool, object] = values.unset, + speech_model: Union[str, object] = values.unset, + hints: Union[str, object] = values.unset, + enable_automatic_punctuation: Union[bool, object] = values.unset, + intelligence_service: Union[str, object] = values.unset, + conversation_configuration: Union[str, object] = values.unset, + conversation_id: Union[str, object] = values.unset, + transcription_configuration_id: Union[str, object] = values.unset, + enable_provider_data: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TranscriptionInstance and return response metadata + + :param name: The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. + :param track: + :param status_callback_url: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track + :param partial_results: Indicates if partial results are going to be sent to the customer + :param language_code: Language code used by the transcription engine, specified in [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) format + :param transcription_engine: Definition of the transcription engine to be used, among those supported by Twilio + :param profanity_filter: indicates if the server will attempt to filter out profanities, replacing all but the initial character in each filtered word with asterisks + :param speech_model: Recognition model used by the transcription engine, among those supported by the provider + :param hints: A Phrase contains words and phrase \\\"hints\\\" so that the speech recognition engine is more likely to recognize them. + :param enable_automatic_punctuation: The provider will add punctuation to recognition result + :param intelligence_service: The SID or unique name of the [Intelligence Service](https://www.twilio.com/docs/conversational-intelligence/api/service-resource) for persisting transcripts and running post-call Language Operators + :param conversation_configuration: The ID of the Conversations Configuration for customizing conversation behavior in Intelligence Service + :param conversation_id: The ID of the Conversation for associating this Transcription with an existing Conversation in Intelligence Service + :param transcription_configuration_id: The ID of the RealTimeTranscription Configuration for configuring all the non-default behaviors in one go. + :param enable_provider_data: Whether the callback includes raw provider data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + name=name, + track=track, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + inbound_track_label=inbound_track_label, + outbound_track_label=outbound_track_label, + partial_results=partial_results, + language_code=language_code, + transcription_engine=transcription_engine, + profanity_filter=profanity_filter, + speech_model=speech_model, + hints=hints, + enable_automatic_punctuation=enable_automatic_punctuation, + intelligence_service=intelligence_service, + conversation_configuration=conversation_configuration, + conversation_id=conversation_id, + transcription_configuration_id=transcription_configuration_id, + enable_provider_data=enable_provider_data, + ) + instance = TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, sid: str) -> TranscriptionContext: """ Constructs a TranscriptionContext diff --git a/twilio/rest/api/v2010/account/call/user_defined_message.py b/twilio/rest/api/v2010/account/call/user_defined_message.py index 4b43383711..d1ed0a91ee 100644 --- a/twilio/rest/api/v2010/account/call/user_defined_message.py +++ b/twilio/rest/api/v2010/account/call/user_defined_message.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -80,16 +81,14 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): ) ) - def create( + def _create( self, content: str, idempotency_key: Union[str, object] = values.unset - ) -> UserDefinedMessageInstance: + ) -> tuple: """ - Create the UserDefinedMessageInstance - - :param content: The User Defined Message in the form of URL-encoded JSON string. - :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + Internal helper for create operation - :returns: The created UserDefinedMessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -100,10 +99,26 @@ def create( ) headers = values.of({"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, 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, @@ -111,16 +126,36 @@ def create( call_sid=self._solution["call_sid"], ) - async def create_async( + def create_with_http_info( self, content: str, idempotency_key: Union[str, object] = values.unset - ) -> UserDefinedMessageInstance: + ) -> ApiResponse: """ - Asynchronously create the UserDefinedMessageInstance + Create the UserDefinedMessageInstance and return response metadata :param content: The User Defined Message in the form of URL-encoded JSON string. :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. - :returns: The created UserDefinedMessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + content=content, idempotency_key=idempotency_key + ) + instance = UserDefinedMessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, content: str, idempotency_key: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -131,10 +166,28 @@ async def create_async( ) headers = values.of({"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, 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, @@ -142,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 677042bd7c..eea6263faa 100644 --- a/twilio/rest/api/v2010/account/call/user_defined_message_subscription.py +++ b/twilio/rest/api/v2010/account/call/user_defined_message_subscription.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[UserDefinedMessageSubscriptionContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserDefinedMessageSubscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserDefinedMessageSubscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -125,6 +145,20 @@ def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserDefinedMessageSubscriptionInstance @@ -132,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: @@ -144,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: """ @@ -183,20 +247,17 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): **self._solution ) - def create( + def _create( self, callback: str, idempotency_key: Union[str, object] = values.unset, method: Union[str, object] = values.unset, - ) -> UserDefinedMessageSubscriptionInstance: + ) -> tuple: """ - Create the UserDefinedMessageSubscriptionInstance + Internal helper for create operation - :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: + tuple: (payload, status_code, headers) """ data = values.of( @@ -208,10 +269,32 @@ def create( ) headers = values.of({"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, + 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,20 +302,43 @@ def create( call_sid=self._solution["call_sid"], ) - async def create_async( + def create_with_http_info( self, callback: str, idempotency_key: Union[str, object] = values.unset, method: Union[str, object] = values.unset, - ) -> UserDefinedMessageSubscriptionInstance: + ) -> ApiResponse: """ - Asynchronously create the UserDefinedMessageSubscriptionInstance + Create the UserDefinedMessageSubscriptionInstance and return response metadata :param callback: The URL we should call using the `method` to send user defined events to your application. URLs must contain a valid hostname (underscores are not permitted). :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. :param method: The HTTP method Twilio will use when requesting the above `Url`. Either `GET` or `POST`. Default is `POST`. - :returns: The created UserDefinedMessageSubscriptionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + callback=callback, idempotency_key=idempotency_key, method=method + ) + instance = UserDefinedMessageSubscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + callback: str, + idempotency_key: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -244,10 +350,32 @@ async def create_async( ) headers = values.of({"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, + 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 074ce8a587..9edc8ce213 100644 --- a/twilio/rest/api/v2010/account/conference/__init__.py +++ b/twilio/rest/api/v2010/account/conference/__init__.py @@ -15,6 +15,7 @@ from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,7 +52,7 @@ class UpdateStatus(object): :ivar date_updated: The date and time in UTC that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar api_version: The API version used to create this conference. :ivar friendly_name: A string that you assigned to describe this conference room. Maximum length is 128 characters. - :ivar region: A string that represents the Twilio Region where the conference audio was mixed. May be `us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, and `jp1`. Basic conference audio will always be mixed in `us1`. Global Conference audio will be mixed nearest to the majority of participants. + :ivar region: A string that represents the Twilio Region where the conference audio was mixed. May be `us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, and `jp1`. Basic conference audio will always be mixed in `us1`. Global Conference audio will be mixed nearest to the majority of participants. :ivar sid: The unique, Twilio-provided string used to identify this Conference resource. :ivar status: :ivar uri: The URI of this resource, relative to `https://api.twilio.com`. @@ -96,6 +97,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[ConferenceContext] = None @property @@ -132,6 +134,24 @@ async def fetch_async(self) -> "ConferenceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConferenceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, @@ -174,6 +194,48 @@ async def update_async( announce_method=announce_method, ) + def update_with_http_info( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConferenceInstance with HTTP info + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + announce_url=announce_url, + announce_method=announce_method, + ) + + async def update_with_http_info_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConferenceInstance with HTTP info + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + announce_url=announce_url, + announce_method=announce_method, + ) + @property def participants(self) -> ParticipantList: """ @@ -222,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 @@ -229,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: """ @@ -249,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, @@ -284,13 +398,34 @@ def update( "AnnounceMethod": announce_method, } ) + 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["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, @@ -298,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, @@ -320,13 +479,34 @@ async def update_async( "AnnounceMethod": announce_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, + 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, @@ -334,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: """ @@ -378,6 +584,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConferenceInstance: :param payload: Payload response from the API """ + return ConferenceInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -511,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, @@ -546,6 +853,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -596,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( @@ -612,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, @@ -660,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, @@ -711,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: """ @@ -726,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: """ @@ -738,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 3706cd24fa..616cad578a 100644 --- a/twilio/rest/api/v2010/account/conference/participant.py +++ b/twilio/rest/api/v2010/account/conference/participant.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -89,6 +90,7 @@ def __init__( "conference_sid": conference_sid, "call_sid": call_sid or self.call_sid, } + self._context: Optional[ParticipantContext] = None @property @@ -126,6 +128,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ParticipantInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ParticipantInstance": """ Fetch the ParticipantInstance @@ -144,6 +164,24 @@ async def fetch_async(self) -> "ParticipantInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, muted: Union[bool, object] = values.unset, @@ -168,7 +206,7 @@ def update( :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param wait_url: The URL we call using the `wait_method` for the music to play while participants are waiting for the conference to start. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. @@ -216,7 +254,7 @@ async def update_async( :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param wait_url: The URL we call using the `wait_method` for the music to play while participants are waiting for the conference to start. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. @@ -240,6 +278,102 @@ async def update_async( call_sid_to_coach=call_sid_to_coach, ) + def update_with_http_info( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + ) + + async def update_with_http_info_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains ``, ``, ``, or `` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -275,6 +409,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ParticipantInstance @@ -282,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: @@ -294,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: @@ -306,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: """ @@ -327,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, @@ -355,25 +589,14 @@ 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": serialize.boolean_to_string(muted), @@ -392,22 +615,17 @@ def update( "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, @@ -423,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. @@ -431,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`. @@ -440,31 +658,20 @@ async def update_async( :returns: The updated ParticipantInstance """ - data = values.of( - { - "Muted": serialize.boolean_to_string(muted), - "Hold": serialize.boolean_to_string(hold), - "HoldUrl": hold_url, - "HoldMethod": hold_method, - "AnnounceUrl": announce_url, - "AnnounceMethod": announce_method, - "WaitUrl": wait_url, - "WaitMethod": wait_method, - "BeepOnExit": serialize.boolean_to_string(beep_on_exit), - "EndConferenceOnExit": serialize.boolean_to_string( - end_conference_on_exit - ), - "Coaching": serialize.boolean_to_string(coaching), - "CallSidToCoach": call_sid_to_coach, - } - ) - - 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, @@ -473,24 +680,242 @@ async def update_async( 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 ParticipantPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + 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: """ - Build an instance of ParticipantInstance + 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 :param payload: Payload response from the API """ + return ParticipantInstance( self._version, payload, @@ -529,7 +954,7 @@ def __init__(self, version: Version, account_sid: str, conference_sid: str): **self._solution ) - def create( + def _create( self, from_: str, to: str, @@ -571,6 +996,7 @@ def create( caller_id: Union[str, object] = values.unset, call_reason: Union[str, object] = values.unset, recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, time_limit: Union[int, object] = values.unset, machine_detection: Union[str, object] = values.unset, machine_detection_timeout: Union[int, object] = values.unset, @@ -581,60 +1007,14 @@ def create( amd_status_callback_method: Union[str, object] = values.unset, trim: Union[str, object] = values.unset, call_token: Union[str, object] = values.unset, - ) -> ParticipantInstance: + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + ) -> tuple: """ - Create the ParticipantInstance - - :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. - :param to: The phone number, SIP address, or Client identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. - :param status_callback_event: The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. - :param label: A label for this participant. If one is supplied, it may subsequently be used to fetch, update or delete the participant. - :param timeout: The number of seconds that we should allow the phone to ring before assuming there is no answer. Can be an integer between `5` and `600`, inclusive. The default value is `60`. We always add a 5-second timeout buffer to outgoing calls, so value of 10 would result in an actual timeout that was closer to 15 seconds. - :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. - :param muted: Whether the agent is muted in the conference. Can be `true` or `false` and the default is `false`. - :param beep: Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. - :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. - :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. - :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). - :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. - :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. - :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. - :param conference_record: Whether to record the conference the participant is joining. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. - :param conference_trim: Whether to trim leading and trailing silence from the conference recording. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. - :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. - :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param conference_status_callback_event: The conference state changes that should generate a call to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `modify`, `speaker`, and `announcement`. Separate multiple values with a space. Defaults to `start end`. - :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. - :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. - :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param sip_auth_username: The SIP username used for authentication. - :param sip_auth_password: The SIP password for authentication. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. - :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. - :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param recording_status_callback_event: The recording state changes that should generate a call to `recording_status_callback`. Can be: `started`, `in-progress`, `paused`, `resumed`, `stopped`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'`. - :param conference_recording_status_callback_event: The conference recording state changes that generate a call to `conference_recording_status_callback`. Can be: `in-progress`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'` - :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. - :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. - :param jitter_buffer_size: Jitter buffer size for the connecting participant. Twilio will use this setting to apply Jitter Buffer before participant's audio is mixed into the conference. Can be: `off`, `small`, `medium`, and `large`. Default to `large`. - :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) - :param caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. - :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) - :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. - :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. - :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). - :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. - :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. - :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. - :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. - :param amd_status_callback: The URL that we should call using the `amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. - :param amd_status_callback_method: The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. - :param trim: Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. - :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + Internal helper for create operation - :returns: The created ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -689,6 +1069,7 @@ def create( "CallerId": caller_id, "CallReason": call_reason, "RecordingTrack": recording_track, + "RecordingConfigurationId": recording_configuration_id, "TimeLimit": time_limit, "MachineDetection": machine_detection, "MachineDetectionTimeout": machine_detection_timeout, @@ -699,22 +1080,21 @@ def create( "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"}) - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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"], + 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, from_: str, to: str, @@ -756,6 +1136,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, @@ -766,12 +1147,14 @@ async def create_async( amd_status_callback_method: Union[str, object] = values.unset, trim: Union[str, object] = values.unset, call_token: Union[str, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, ) -> ParticipantInstance: """ - Asynchronously create the ParticipantInstance + Create the ParticipantInstance :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. - :param to: The phone number, SIP address, or Client identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. + :param to: The phone number, SIP address, Client, TwiML App identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. TwiML App identifiers are formatted `app:`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. :param status_callback_event: The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. @@ -782,7 +1165,7 @@ async def create_async( :param beep: Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. - :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. @@ -796,7 +1179,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'`. @@ -808,6 +1191,7 @@ async def create_async( :param caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. @@ -818,10 +1202,308 @@ async def create_async( :param amd_status_callback_method: The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. :param trim: Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param 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, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + def create_with_http_info( + self, + from_: str, + to: str, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + label: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[List[str], object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + conference_recording_status_callback_event: Union[ + List[str], object + ] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + amd_status_callback: Union[str, object] = values.unset, + amd_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ParticipantInstance and return response metadata + + :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. + :param to: The phone number, SIP address, Client, TwiML App identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. TwiML App identifiers are formatted `app:`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. + :param status_callback_event: The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. + :param label: A label for this participant. If one is supplied, it may subsequently be used to fetch, update or delete the participant. + :param timeout: The number of seconds that we should allow the phone to ring before assuming there is no answer. Can be an integer between `5` and `600`, inclusive. The default value is `60`. We always add a 5-second timeout buffer to outgoing calls, so value of 10 would result in an actual timeout that was closer to 15 seconds. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Can be `true` or `false` and the default is `false`. + :param beep: Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_record: Whether to record the conference the participant is joining. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from the conference recording. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference state changes that should generate a call to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `modify`, `speaker`, and `announcement`. Separate multiple values with a space. Defaults to `start end`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param recording_status_callback_event: The recording state changes that should generate a call to `recording_status_callback`. Can be: `started`, `in-progress`, `paused`, `resumed`, `stopped`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'`. + :param conference_recording_status_callback_event: The conference recording state changes that generate a call to `conference_recording_status_callback`. Can be: `in-progress`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'` + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + :param jitter_buffer_size: Jitter buffer size for the connecting participant. Twilio will use this setting to apply Jitter Buffer before participant's audio is mixed into the conference. Can be: `off`, `small`, `medium`, and `large`. Default to `large`. + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param amd_status_callback: The URL that we should call using the `amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param amd_status_callback_method: The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param 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) + + 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_, @@ -874,6 +1556,7 @@ async def create_async( "CallerId": caller_id, "CallReason": call_reason, "RecordingTrack": recording_track, + "RecordingConfigurationId": recording_configuration_id, "TimeLimit": time_limit, "MachineDetection": machine_detection, "MachineDetectionTimeout": machine_detection_timeout, @@ -884,20 +1567,366 @@ async def create_async( "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"}) - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + 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. + + :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, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + async def create_with_http_info_async( + self, + from_: str, + to: str, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + label: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[List[str], object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + conference_recording_status_callback_event: Union[ + List[str], object + ] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + recording_configuration_id: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + amd_status_callback: Union[str, object] = values.unset, + amd_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ParticipantInstance and return response metadata + + :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. + :param to: The phone number, SIP address, Client, TwiML App identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. TwiML App identifiers are formatted `app:`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. + :param status_callback_event: The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. + :param label: A label for this participant. If one is supplied, it may subsequently be used to fetch, update or delete the participant. + :param timeout: The number of seconds that we should allow the phone to ring before assuming there is no answer. Can be an integer between `5` and `600`, inclusive. The default value is `60`. We always add a 5-second timeout buffer to outgoing calls, so value of 10 would result in an actual timeout that was closer to 15 seconds. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Can be `true` or `false` and the default is `false`. + :param beep: Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [ TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_record: Whether to record the conference the participant is joining. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from the conference recording. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference state changes that should generate a call to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `modify`, `speaker`, and `announcement`. Separate multiple values with a space. Defaults to `start end`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param recording_status_callback_event: The recording state changes that should generate a call to `recording_status_callback`. Can be: `started`, `in-progress`, `paused`, `resumed`, `stopped`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'`. + :param conference_recording_status_callback_event: The conference recording state changes that generate a call to `conference_recording_status_callback`. Can be: `in-progress`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'` + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + :param jitter_buffer_size: Jitter buffer size for the connecting participant. Twilio will use this setting to apply Jitter Buffer before participant's audio is mixed into the conference. Can be: `off`, `small`, `medium`, and `large`. Default to `large`. + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. + :param recording_configuration_id: The identifier of the configuration to be used when creating and processing the recording + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param amd_status_callback: The URL that we should call using the `amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param amd_status_callback_method: The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param 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, @@ -965,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, @@ -990,6 +2083,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( muted=muted, @@ -1025,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( @@ -1036,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, @@ -1069,8 +2232,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, @@ -1105,10 +2274,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 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: """ @@ -1120,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: """ @@ -1132,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 dfb1d406ee..cca644f741 100644 --- a/twilio/rest/api/v2010/account/conference/recording.py +++ b/twilio/rest/api/v2010/account/conference/recording.py @@ -15,6 +15,7 @@ from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -102,6 +103,7 @@ def __init__( "conference_sid": conference_sid, "sid": sid or self.sid, } + self._context: Optional[RecordingContext] = None @property @@ -139,6 +141,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RecordingInstance": """ Fetch the RecordingInstance @@ -157,6 +177,24 @@ async def fetch_async(self) -> "RecordingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: "RecordingInstance.Status", @@ -193,6 +231,42 @@ async def update_async( pause_behavior=pause_behavior, ) + def update_with_http_info( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RecordingInstance with HTTP info + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + pause_behavior=pause_behavior, + ) + + async def update_with_http_info_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RecordingInstance with HTTP info + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + pause_behavior=pause_behavior, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -228,6 +302,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RecordingInstance @@ -235,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: @@ -247,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: @@ -259,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: """ @@ -280,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" - 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: "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, @@ -328,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({}) + + 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, @@ -362,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 @@ -380,6 +638,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: :param payload: Payload response from the API """ + return RecordingInstance( self._version, payload, @@ -490,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, @@ -515,6 +844,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -550,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( @@ -561,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, @@ -594,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, @@ -630,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: """ @@ -645,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: """ @@ -657,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 722e4e9b3e..6f6f0513c1 100644 --- a/twilio/rest/api/v2010/account/connect_app.py +++ b/twilio/rest/api/v2010/account/connect_app.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[ConnectAppContext] = None @property @@ -110,6 +112,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectAppInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectAppInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ConnectAppInstance": """ Fetch the ConnectAppInstance @@ -128,6 +148,24 @@ async def fetch_async(self) -> "ConnectAppInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectAppInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectAppInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, authorize_redirect_url: Union[str, object] = values.unset, @@ -204,6 +242,82 @@ async def update_async( permissions=permissions, ) + def update_with_http_info( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ConnectAppInstance with HTTP info + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) + + async def update_with_http_info_async( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectAppInstance with HTTP info + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -235,6 +349,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ConnectAppInstance @@ -242,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: @@ -254,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: @@ -266,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: """ @@ -286,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, @@ -311,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, @@ -338,13 +543,53 @@ def update( "Permissions": serialize.map(permissions, lambda e: e), } ) + 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, + 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, @@ -352,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, @@ -364,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. @@ -377,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, @@ -391,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" + + 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, + 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, @@ -405,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 @@ -423,6 +791,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConnectAppInstance: :param payload: Payload response from the API """ + return ConnectAppInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -504,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, @@ -523,6 +942,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -549,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( @@ -557,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, @@ -581,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, @@ -608,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: """ @@ -623,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: """ @@ -635,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 d1001a7cae..948519d653 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -87,6 +88,7 @@ class VoiceReceiveMode(object): :ivar emergency_address_status: :ivar bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. :ivar status: + :ivar type: The phone number type. """ def __init__( @@ -148,11 +150,13 @@ def __init__( ] = payload.get("emergency_address_status") self.bundle_sid: Optional[str] = payload.get("bundle_sid") self.status: Optional[str] = payload.get("status") + self.type: Optional[str] = payload.get("type") self._solution = { "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[IncomingPhoneNumberContext] = None @property @@ -189,6 +193,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IncomingPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IncomingPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "IncomingPhoneNumberInstance": """ Fetch the IncomingPhoneNumberInstance @@ -207,6 +229,24 @@ async def fetch_async(self) -> "IncomingPhoneNumberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IncomingPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IncomingPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, account_sid: Union[str, object] = values.unset, @@ -377,111 +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, @@ -510,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`. @@ -538,52 +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": 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, - } - ) - - 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, @@ -612,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`. @@ -640,49 +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": 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, - } - ) - - 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 @@ -690,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: """ @@ -705,17 +601,744 @@ 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): +class IncomingPhoneNumberContext(InstanceContext): - def get_instance(self, payload: Dict[str, Any]) -> IncomingPhoneNumberInstance: + def __init__(self, version: Version, account_sid: str, sid: str): """ - Build an instance of IncomingPhoneNumberInstance + 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"] ) @@ -735,24 +1358,102 @@ 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, @@ -814,6 +1515,165 @@ 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( { @@ -847,12 +1707,12 @@ def create( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return IncomingPhoneNumberInstance( - 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( @@ -916,46 +1776,127 @@ async def create_async( :returns: The created IncomingPhoneNumberInstance """ - - 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, - } + 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, ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_async( + self, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + area_code: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the IncomingPhoneNumberInstance and return response metadata - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + :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). - return IncomingPhoneNumberInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + identity_sid=identity_sid, + address_sid=address_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + phone_number=phone_number, + area_code=area_code, + ) + instance = IncomingPhoneNumberInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -1035,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, @@ -1062,6 +2079,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( beta=beta, @@ -1100,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( @@ -1112,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, @@ -1148,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, @@ -1187,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: """ @@ -1202,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: """ @@ -1214,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 a6ced82856..83acaedda3 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -73,6 +74,7 @@ def __init__( "resource_sid": resource_sid, "sid": sid or self.sid, } + self._context: Optional[AssignedAddOnContext] = None @property @@ -110,6 +112,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssignedAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssignedAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AssignedAddOnInstance": """ Fetch the AssignedAddOnInstance @@ -128,6 +148,24 @@ async def fetch_async(self) -> "AssignedAddOnInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssignedAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssignedAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def extensions(self) -> AssignedAddOnExtensionList: """ @@ -170,6 +208,20 @@ def __init__(self, version: Version, account_sid: str, resource_sid: str, sid: s self._extensions: Optional[AssignedAddOnExtensionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AssignedAddOnInstance @@ -177,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: @@ -189,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: @@ -201,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: """ @@ -222,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: @@ -268,6 +406,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AssignedAddOnInstance: :param payload: Payload response from the API """ + return AssignedAddOnInstance( self._version, payload, @@ -306,13 +445,12 @@ def __init__(self, version: Version, account_sid: str, resource_sid: str): **self._solution ) - def create(self, installed_add_on_sid: str) -> AssignedAddOnInstance: + def _create(self, installed_add_on_sid: str) -> tuple: """ - Create the AssignedAddOnInstance - - :param installed_add_on_sid: The SID that identifies the Add-on installation. + Internal helper for create operation - :returns: The created AssignedAddOnInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -322,10 +460,23 @@ def create(self, installed_add_on_sid: str) -> AssignedAddOnInstance: ) headers = values.of({"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, 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, @@ -333,13 +484,31 @@ def create(self, installed_add_on_sid: str) -> AssignedAddOnInstance: resource_sid=self._solution["resource_sid"], ) - async def create_async(self, installed_add_on_sid: str) -> AssignedAddOnInstance: + def create_with_http_info(self, installed_add_on_sid: str) -> ApiResponse: """ - Asynchronously create the AssignedAddOnInstance + Create the AssignedAddOnInstance and return response metadata :param installed_add_on_sid: The SID that identifies the Add-on installation. - :returns: The created AssignedAddOnInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + installed_add_on_sid=installed_add_on_sid + ) + instance = AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, installed_add_on_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -349,10 +518,25 @@ async def create_async(self, installed_add_on_sid: str) -> AssignedAddOnInstance ) headers = values.of({"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, 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, @@ -360,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, @@ -410,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, @@ -429,6 +684,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -455,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( @@ -463,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, @@ -487,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, @@ -514,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: """ @@ -529,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: """ @@ -541,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 18504cafd8..f9d3e5d83d 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/assigned_add_on_extension.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/assigned_add_on_extension.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( "assigned_add_on_sid": assigned_add_on_sid, "sid": sid or self.sid, } + self._context: Optional[AssignedAddOnExtensionContext] = None @property @@ -99,6 +101,24 @@ async def fetch_async(self) -> "AssignedAddOnExtensionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssignedAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,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 @@ -148,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"], @@ -162,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: """ @@ -170,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"], @@ -184,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: """ @@ -203,6 +281,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AssignedAddOnExtensionInstanc :param payload: Payload response from the API """ + return AssignedAddOnExtensionInstance( self._version, payload, @@ -300,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, @@ -319,6 +448,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -345,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( @@ -353,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, @@ -377,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, @@ -404,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 ) - return AssignedAddOnExtensionPage(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 AssignedAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AssignedAddOnExtensionPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> AssignedAddOnExtensionPage: """ @@ -419,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: """ @@ -431,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 ca7baa8552..06ce14ba9f 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/local.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/local.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -159,6 +160,7 @@ def get_instance(self, payload: Dict[str, Any]) -> LocalInstance: :param payload: Payload response from the API """ + return LocalInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -192,7 +194,7 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) - def create( + def _create( self, phone_number: str, api_version: Union[str, object] = values.unset, @@ -219,35 +221,12 @@ def create( "LocalInstance.VoiceReceiveMode", object ] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> LocalInstance: + ) -> tuple: """ - Create the LocalInstance + Internal helper for create operation - :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. - :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. - :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. - :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. - :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. - :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. - :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. - :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. - :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. - :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. - :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. - :param emergency_status: - :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. - :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. - :param voice_receive_mode: - :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - - :returns: The created LocalInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -281,15 +260,101 @@ def create( ) headers = values.of({"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, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> LocalInstance: + """ + Create the LocalInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created LocalInstance + """ + payload, _, _ = self._create( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) return LocalInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, phone_number: str, api_version: Union[str, object] = values.unset, @@ -316,9 +381,9 @@ async def create_async( "LocalInstance.VoiceReceiveMode", object ] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> LocalInstance: + ) -> ApiResponse: """ - Asynchronously create the LocalInstance + Create the LocalInstance and return response metadata :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. @@ -344,7 +409,71 @@ async def create_async( :param voice_receive_mode: :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - :returns: The created LocalInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -378,14 +507,187 @@ async def create_async( ) headers = values.of({"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, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> LocalInstance: + """ + Asynchronously create the LocalInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created LocalInstance + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) return LocalInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the LocalInstance and return response metadata + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, beta: Union[bool, object] = values.unset, @@ -464,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, @@ -491,6 +869,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( beta=beta, @@ -529,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( @@ -541,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, @@ -577,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, @@ -616,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: """ @@ -631,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: """ @@ -643,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 830897b178..2087c91ae3 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -159,6 +160,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MobileInstance: :param payload: Payload response from the API """ + return MobileInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -192,7 +194,7 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) - def create( + def _create( self, phone_number: str, api_version: Union[str, object] = values.unset, @@ -221,35 +223,12 @@ def create( "MobileInstance.VoiceReceiveMode", object ] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> MobileInstance: + ) -> tuple: """ - Create the MobileInstance + Internal helper for create operation - :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. - :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. - :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. - :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. - :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. - :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. - :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. - :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. - :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. - :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. - :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. - :param emergency_status: - :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. - :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. - :param voice_receive_mode: - :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - - :returns: The created MobileInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -283,15 +262,103 @@ def create( ) headers = values.of({"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, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> MobileInstance: + """ + Create the MobileInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created MobileInstance + """ + payload, _, _ = self._create( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) return MobileInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, phone_number: str, api_version: Union[str, object] = values.unset, @@ -320,9 +387,9 @@ async def create_async( "MobileInstance.VoiceReceiveMode", object ] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> MobileInstance: + ) -> ApiResponse: """ - Asynchronously create the MobileInstance + Create the MobileInstance and return response metadata :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. @@ -348,7 +415,73 @@ async def create_async( :param voice_receive_mode: :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - :returns: The created MobileInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -382,14 +515,191 @@ async def create_async( ) headers = values.of({"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, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> MobileInstance: + """ + Asynchronously create the MobileInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created MobileInstance + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) return MobileInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the MobileInstance and return response metadata + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, beta: Union[bool, object] = values.unset, @@ -468,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, @@ -495,6 +881,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( beta=beta, @@ -533,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( @@ -545,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, @@ -581,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, @@ -620,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: """ @@ -635,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: """ @@ -647,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 8625e318c6..c4597aa459 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -159,6 +160,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TollFreeInstance: :param payload: Payload response from the API """ + return TollFreeInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -192,7 +194,7 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) - def create( + def _create( self, phone_number: str, api_version: Union[str, object] = values.unset, @@ -221,35 +223,12 @@ def create( "TollFreeInstance.VoiceReceiveMode", object ] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> TollFreeInstance: + ) -> tuple: """ - Create the TollFreeInstance + Internal helper for create operation - :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. - :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. - :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. - :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. - :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. - :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. - :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. - :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. - :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. - :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. - :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. - :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. - :param emergency_status: - :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. - :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. - :param voice_receive_mode: - :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - - :returns: The created TollFreeInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -283,15 +262,103 @@ def create( ) headers = values.of({"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, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> TollFreeInstance: + """ + Create the TollFreeInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created TollFreeInstance + """ + payload, _, _ = self._create( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) return TollFreeInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, phone_number: str, api_version: Union[str, object] = values.unset, @@ -320,9 +387,9 @@ async def create_async( "TollFreeInstance.VoiceReceiveMode", object ] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> TollFreeInstance: + ) -> ApiResponse: """ - Asynchronously create the TollFreeInstance + Create the TollFreeInstance and return response metadata :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. @@ -348,7 +415,73 @@ async def create_async( :param voice_receive_mode: :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. - :returns: The created TollFreeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -382,14 +515,191 @@ async def create_async( ) headers = values.of({"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, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> TollFreeInstance: + """ + Asynchronously create the TollFreeInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created TollFreeInstance + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) return TollFreeInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TollFreeInstance and return response metadata + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + identity_sid=identity_sid, + address_sid=address_sid, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + bundle_sid=bundle_sid, + ) + instance = TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, beta: Union[bool, object] = values.unset, @@ -468,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, @@ -495,6 +881,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( beta=beta, @@ -533,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( @@ -545,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, @@ -581,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, @@ -620,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: """ @@ -635,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: """ @@ -647,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 68a9feb0e1..2683e7ab3c 100644 --- a/twilio/rest/api/v2010/account/key.py +++ b/twilio/rest/api/v2010/account/key.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[KeyContext] = None @property @@ -88,6 +90,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the KeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "KeyInstance": """ Fetch the KeyInstance @@ -106,6 +126,24 @@ async def fetch_async(self) -> "KeyInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the KeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, friendly_name: Union[str, object] = values.unset) -> "KeyInstance": """ Update the KeyInstance @@ -132,6 +170,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the KeyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KeyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -161,6 +227,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): } self._uri = "/Accounts/{account_sid}/Keys/{sid}.json".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the KeyInstance @@ -168,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: @@ -180,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: @@ -192,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: """ @@ -212,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, @@ -225,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({}) - 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) -> 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, @@ -252,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" + + 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 + ) -> 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, @@ -281,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 @@ -299,6 +529,7 @@ def get_instance(self, payload: Dict[str, Any]) -> KeyInstance: :param payload: Payload response from the API """ + return KeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -380,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, @@ -399,6 +680,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -425,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( @@ -433,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, @@ -457,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, @@ -484,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: """ @@ -499,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: """ @@ -511,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 7eb11d3889..38182a2c9b 100644 --- a/twilio/rest/api/v2010/account/message/__init__.py +++ b/twilio/rest/api/v2010/account/message/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,9 @@ class Status(object): PARTIALLY_DELIVERED = "partially_delivered" CANCELED = "canceled" + class TrafficType(object): + FREE = "free" + class UpdateStatus(object): CANCELED = "canceled" @@ -73,7 +77,7 @@ class UpdateStatus(object): :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`. + :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. @@ -82,7 +86,7 @@ class UpdateStatus(object): :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`. + :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 subresource_uris: A list of related resources identified by their URIs relative to `https://api.twilio.com` @@ -130,6 +134,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -166,6 +171,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -184,6 +207,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, body: Union[str, object] = values.unset, @@ -220,6 +261,42 @@ async def update_async( status=status, ) + def update_with_http_info( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + body=body, + status=status, + ) + + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + body=body, + status=status, + ) + @property def feedback(self) -> FeedbackList: """ @@ -268,6 +345,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._feedback: Optional[FeedbackList] = None self._media: Optional[MediaList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MessageInstance @@ -275,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: @@ -287,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: @@ -299,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: """ @@ -319,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 new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string - :param status: + Internal helper for update operation - :returns: The updated MessageInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Body": body, "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, + 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, @@ -365,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 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({}) + + 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, + 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, @@ -398,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: """ @@ -442,6 +695,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -473,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, @@ -491,6 +745,7 @@ def create( ] = values.unset, smart_encoded: Union[bool, object] = values.unset, persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, shorten_urls: Union[bool, object] = values.unset, schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, send_at: Union[datetime, object] = values.unset, @@ -498,39 +753,17 @@ def create( content_variables: Union[str, object] = values.unset, risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, from_: Union[str, object] = values.unset, + fallback_from: Union[str, object] = values.unset, messaging_service_sid: Union[str, object] = values.unset, body: Union[str, object] = values.unset, media_url: Union[List[str], object] = values.unset, content_sid: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance - - :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. - :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). - :param application_sid: The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. - :param max_price: [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. - :param provide_feedback: Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. - :param attempt: Total number of attempts made (including this request) to send the message regardless of the provider used - :param validity_period: The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) - :param force_delivery: Reserved - :param content_retention: - :param address_retention: - :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. - :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). - :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. - :param schedule_type: - :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. - :param send_as_mms: If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. - :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. - :param risk_check: - :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. - :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). - :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. - :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + Internal helper for create operation - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -547,6 +780,7 @@ def create( "AddressRetention": address_retention, "SmartEncoded": serialize.boolean_to_string(smart_encoded), "PersistentAction": serialize.map(persistent_action, lambda e: e), + "TrafficType": traffic_type, "ShortenUrls": serialize.boolean_to_string(shorten_urls), "ScheduleType": schedule_type, "SendAt": serialize.iso8601_datetime(send_at), @@ -554,6 +788,7 @@ def create( "ContentVariables": content_variables, "RiskCheck": risk_check, "From": from_, + "FallbackFrom": fallback_from, "MessagingServiceSid": messaging_service_sid, "Body": body, "MediaUrl": serialize.map(media_url, lambda e: e), @@ -562,15 +797,15 @@ def create( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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, @@ -588,6 +823,7 @@ async def create_async( ] = values.unset, smart_encoded: Union[bool, object] = values.unset, persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, shorten_urls: Union[bool, object] = values.unset, schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, send_at: Union[datetime, object] = values.unset, @@ -595,13 +831,14 @@ async def create_async( content_variables: Union[str, object] = values.unset, risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, from_: Union[str, object] = values.unset, + fallback_from: Union[str, object] = values.unset, messaging_service_sid: Union[str, object] = values.unset, body: Union[str, object] = values.unset, media_url: Union[List[str], object] = values.unset, content_sid: Union[str, object] = values.unset, ) -> MessageInstance: """ - Asynchronously create the MessageInstance + Create the MessageInstance :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). @@ -615,6 +852,7 @@ async def create_async( :param address_retention: :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). + :param traffic_type: :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. :param schedule_type: :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. @@ -622,6 +860,7 @@ async def create_async( :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. :param risk_check: :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. + :param fallback_from: A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message. :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. @@ -629,45 +868,400 @@ async def create_async( :returns: The created MessageInstance """ - - data = values.of( - { - "To": to, - "StatusCallback": status_callback, - "ApplicationSid": application_sid, - "MaxPrice": max_price, - "ProvideFeedback": serialize.boolean_to_string(provide_feedback), - "Attempt": attempt, - "ValidityPeriod": validity_period, - "ForceDelivery": serialize.boolean_to_string(force_delivery), - "ContentRetention": content_retention, - "AddressRetention": address_retention, - "SmartEncoded": serialize.boolean_to_string(smart_encoded), - "PersistentAction": serialize.map(persistent_action, lambda e: e), - "ShortenUrls": serialize.boolean_to_string(shorten_urls), - "ScheduleType": schedule_type, - "SendAt": serialize.iso8601_datetime(send_at), - "SendAsMms": serialize.boolean_to_string(send_as_mms), - "ContentVariables": content_variables, - "RiskCheck": risk_check, - "From": from_, - "MessagingServiceSid": messaging_service_sid, - "Body": body, - "MediaUrl": serialize.map(media_url, lambda e: e), - "ContentSid": content_sid, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._create( + to=to, + status_callback=status_callback, + application_sid=application_sid, + max_price=max_price, + provide_feedback=provide_feedback, + attempt=attempt, + validity_period=validity_period, + force_delivery=force_delivery, + content_retention=content_retention, + address_retention=address_retention, + smart_encoded=smart_encoded, + persistent_action=persistent_action, + traffic_type=traffic_type, + shorten_urls=shorten_urls, + schedule_type=schedule_type, + send_at=send_at, + send_as_mms=send_as_mms, + content_variables=content_variables, + risk_check=risk_check, + from_=from_, + fallback_from=fallback_from, + messaging_service_sid=messaging_service_sid, + body=body, + media_url=media_url, + content_sid=content_sid, ) - return MessageInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - def stream( + def create_with_http_info( + self, + to: str, + status_callback: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + max_price: Union[float, object] = values.unset, + provide_feedback: Union[bool, object] = values.unset, + attempt: Union[int, object] = values.unset, + validity_period: Union[int, object] = values.unset, + force_delivery: Union[bool, object] = values.unset, + content_retention: Union[ + "MessageInstance.ContentRetention", object + ] = values.unset, + address_retention: Union[ + "MessageInstance.AddressRetention", object + ] = values.unset, + smart_encoded: Union[bool, object] = values.unset, + persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, + shorten_urls: Union[bool, object] = values.unset, + schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, + send_at: Union[datetime, object] = values.unset, + send_as_mms: Union[bool, object] = values.unset, + content_variables: Union[str, object] = values.unset, + risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, + from_: Union[str, object] = values.unset, + fallback_from: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + content_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the MessageInstance and return response metadata + + :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. + :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). + :param application_sid: The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. + :param max_price: [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. + :param provide_feedback: Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. + :param attempt: Total number of attempts made (including this request) to send the message regardless of the provider used + :param validity_period: The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) + :param force_delivery: Reserved + :param content_retention: + :param address_retention: + :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. + :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). + :param traffic_type: + :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. + :param schedule_type: + :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. + :param send_as_mms: If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. + :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. + :param risk_check: + :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. + :param fallback_from: A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, + status_callback=status_callback, + application_sid=application_sid, + max_price=max_price, + provide_feedback=provide_feedback, + attempt=attempt, + validity_period=validity_period, + force_delivery=force_delivery, + content_retention=content_retention, + address_retention=address_retention, + smart_encoded=smart_encoded, + persistent_action=persistent_action, + traffic_type=traffic_type, + shorten_urls=shorten_urls, + schedule_type=schedule_type, + send_at=send_at, + send_as_mms=send_as_mms, + content_variables=content_variables, + risk_check=risk_check, + from_=from_, + fallback_from=fallback_from, + messaging_service_sid=messaging_service_sid, + body=body, + media_url=media_url, + content_sid=content_sid, + ) + instance = MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + to: str, + status_callback: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + max_price: Union[float, object] = values.unset, + provide_feedback: Union[bool, object] = values.unset, + attempt: Union[int, object] = values.unset, + validity_period: Union[int, object] = values.unset, + force_delivery: Union[bool, object] = values.unset, + content_retention: Union[ + "MessageInstance.ContentRetention", object + ] = values.unset, + address_retention: Union[ + "MessageInstance.AddressRetention", object + ] = values.unset, + smart_encoded: Union[bool, object] = values.unset, + persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, + shorten_urls: Union[bool, object] = values.unset, + schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, + send_at: Union[datetime, object] = values.unset, + send_as_mms: Union[bool, object] = values.unset, + content_variables: Union[str, object] = values.unset, + risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, + from_: Union[str, object] = values.unset, + fallback_from: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + content_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "To": to, + "StatusCallback": status_callback, + "ApplicationSid": application_sid, + "MaxPrice": max_price, + "ProvideFeedback": serialize.boolean_to_string(provide_feedback), + "Attempt": attempt, + "ValidityPeriod": validity_period, + "ForceDelivery": serialize.boolean_to_string(force_delivery), + "ContentRetention": content_retention, + "AddressRetention": address_retention, + "SmartEncoded": serialize.boolean_to_string(smart_encoded), + "PersistentAction": serialize.map(persistent_action, lambda e: e), + "TrafficType": traffic_type, + "ShortenUrls": serialize.boolean_to_string(shorten_urls), + "ScheduleType": schedule_type, + "SendAt": serialize.iso8601_datetime(send_at), + "SendAsMms": serialize.boolean_to_string(send_as_mms), + "ContentVariables": content_variables, + "RiskCheck": risk_check, + "From": from_, + "FallbackFrom": fallback_from, + "MessagingServiceSid": messaging_service_sid, + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + "ContentSid": content_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, + to: str, + status_callback: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + max_price: Union[float, object] = values.unset, + provide_feedback: Union[bool, object] = values.unset, + attempt: Union[int, object] = values.unset, + validity_period: Union[int, object] = values.unset, + force_delivery: Union[bool, object] = values.unset, + content_retention: Union[ + "MessageInstance.ContentRetention", object + ] = values.unset, + address_retention: Union[ + "MessageInstance.AddressRetention", object + ] = values.unset, + smart_encoded: Union[bool, object] = values.unset, + persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, + shorten_urls: Union[bool, object] = values.unset, + schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, + send_at: Union[datetime, object] = values.unset, + send_as_mms: Union[bool, object] = values.unset, + content_variables: Union[str, object] = values.unset, + risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, + from_: Union[str, object] = values.unset, + fallback_from: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + content_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. + :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). + :param application_sid: The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. + :param max_price: [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. + :param provide_feedback: Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. + :param attempt: Total number of attempts made (including this request) to send the message regardless of the provider used + :param validity_period: The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) + :param force_delivery: Reserved + :param content_retention: + :param address_retention: + :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. + :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). + :param traffic_type: + :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. + :param schedule_type: + :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. + :param send_as_mms: If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. + :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. + :param risk_check: + :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. + :param fallback_from: A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: The created MessageInstance + """ + payload, _, _ = await self._create_async( + to=to, + status_callback=status_callback, + application_sid=application_sid, + max_price=max_price, + provide_feedback=provide_feedback, + attempt=attempt, + validity_period=validity_period, + force_delivery=force_delivery, + content_retention=content_retention, + address_retention=address_retention, + smart_encoded=smart_encoded, + persistent_action=persistent_action, + traffic_type=traffic_type, + shorten_urls=shorten_urls, + schedule_type=schedule_type, + send_at=send_at, + send_as_mms=send_as_mms, + content_variables=content_variables, + risk_check=risk_check, + from_=from_, + fallback_from=fallback_from, + messaging_service_sid=messaging_service_sid, + body=body, + media_url=media_url, + content_sid=content_sid, + ) + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_with_http_info_async( + self, + to: str, + status_callback: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + max_price: Union[float, object] = values.unset, + provide_feedback: Union[bool, object] = values.unset, + attempt: Union[int, object] = values.unset, + validity_period: Union[int, object] = values.unset, + force_delivery: Union[bool, object] = values.unset, + content_retention: Union[ + "MessageInstance.ContentRetention", object + ] = values.unset, + address_retention: Union[ + "MessageInstance.AddressRetention", object + ] = values.unset, + smart_encoded: Union[bool, object] = values.unset, + persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, + shorten_urls: Union[bool, object] = values.unset, + schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, + send_at: Union[datetime, object] = values.unset, + send_as_mms: Union[bool, object] = values.unset, + content_variables: Union[str, object] = values.unset, + risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, + from_: Union[str, object] = values.unset, + fallback_from: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + content_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. + :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). + :param application_sid: The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. + :param max_price: [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. + :param provide_feedback: Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. + :param attempt: Total number of attempts made (including this request) to send the message regardless of the provider used + :param validity_period: The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) + :param force_delivery: Reserved + :param content_retention: + :param address_retention: + :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. + :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). + :param traffic_type: + :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. + :param schedule_type: + :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. + :param send_as_mms: If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. + :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. + :param risk_check: + :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. + :param fallback_from: A fallback SMS sender to use when the recipient cannot be reached over RCS. This parameter may only be used when also providing a [Messaging Service](https://twilio.com/docs/messaging/services) containing an RCS sender. The fallback SMS sender must be either a Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), or [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), hosted within Twilio and belong to the Account creating the Message. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, + status_callback=status_callback, + application_sid=application_sid, + max_price=max_price, + provide_feedback=provide_feedback, + attempt=attempt, + validity_period=validity_period, + force_delivery=force_delivery, + content_retention=content_retention, + address_retention=address_retention, + smart_encoded=smart_encoded, + persistent_action=persistent_action, + traffic_type=traffic_type, + shorten_urls=shorten_urls, + schedule_type=schedule_type, + send_at=send_at, + send_as_mms=send_as_mms, + content_variables=content_variables, + risk_check=risk_check, + from_=from_, + fallback_from=fallback_from, + messaging_service_sid=messaging_service_sid, + body=body, + media_url=media_url, + content_sid=content_sid, + ) + instance = MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( self, to: Union[str, object] = values.unset, from_: Union[str, object] = values.unset, @@ -683,8 +1277,8 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` - :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). @@ -725,8 +1319,8 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` - :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). @@ -751,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, @@ -766,8 +1442,8 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` - :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). @@ -780,6 +1456,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( to=to, @@ -807,8 +1484,8 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` - :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param str to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param str from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). @@ -821,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( @@ -834,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, @@ -849,8 +1607,8 @@ def page( Retrieve a single page of MessageInstance records from the API. Request is executed immediately - :param to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` - :param from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. :param date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). @@ -873,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, @@ -891,8 +1655,8 @@ async def page_async( Asynchronously retrieve a single page of MessageInstance records from the API. Request is executed immediately - :param to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` - :param from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param to: Filter by recipient. For example: Set this parameter to `+15558881111` to retrieve a list of Message resources sent to `+15558881111`. + :param from_: Filter by sender. For example: Set this parameter to `+15552229999` to retrieve a list of Message resources sent by `+15552229999`. :param date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). :param date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). @@ -915,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: """ @@ -930,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: """ @@ -942,7 +1810,7 @@ async def get_page_async(self, target_url: str) -> MessagePage: :returns: Page of MessageInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MessagePage(self._version, response, self._solution) + return MessagePage(self._version, response, solution=self._solution) def get(self, sid: str) -> MessageContext: """ diff --git a/twilio/rest/api/v2010/account/message/feedback.py b/twilio/rest/api/v2010/account/message/feedback.py index 797c9a7331..5922ead4e2 100644 --- a/twilio/rest/api/v2010/account/message/feedback.py +++ b/twilio/rest/api/v2010/account/message/feedback.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -95,15 +96,14 @@ def __init__(self, version: Version, account_sid: str, message_sid: str): ) ) - def create( + def _create( self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset - ) -> FeedbackInstance: + ) -> tuple: """ - Create the FeedbackInstance + Internal helper for create operation - :param outcome: - - :returns: The created FeedbackInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -113,10 +113,25 @@ def create( ) headers = values.of({"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, 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, @@ -124,15 +139,33 @@ def create( message_sid=self._solution["message_sid"], ) - async def create_async( + def create_with_http_info( self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset - ) -> FeedbackInstance: + ) -> ApiResponse: """ - Asynchronously create the FeedbackInstance + Create the FeedbackInstance and return response metadata :param outcome: - :returns: The created FeedbackInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(outcome=outcome) + instance = FeedbackInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -142,10 +175,25 @@ async def create_async( ) headers = values.of({"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, 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, @@ -153,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 4068d0c35d..d15bc20f18 100644 --- a/twilio/rest/api/v2010/account/message/media.py +++ b/twilio/rest/api/v2010/account/message/media.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( "message_sid": message_sid, "sid": sid or self.sid, } + self._context: Optional[MediaContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MediaInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MediaInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MediaInstance": """ Fetch the MediaInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "MediaInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MediaInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MediaInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -150,6 +188,20 @@ def __init__(self, version: Version, account_sid: str, message_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MediaInstance @@ -157,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: @@ -169,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: @@ -181,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: """ @@ -202,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: """ @@ -234,6 +372,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MediaInstance: :param payload: Payload response from the API """ + return MediaInstance( self._version, payload, @@ -344,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, @@ -369,6 +578,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -404,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( @@ -415,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, @@ -448,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, @@ -484,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: """ @@ -499,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: """ @@ -511,7 +888,7 @@ async def get_page_async(self, target_url: str) -> MediaPage: :returns: Page of MediaInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return MediaPage(self._version, response, self._solution) + return MediaPage(self._version, response, solution=self._solution) def get(self, sid: str) -> MediaContext: """ diff --git a/twilio/rest/api/v2010/account/new_key.py b/twilio/rest/api/v2010/account/new_key.py index fcefed5b62..525891af56 100644 --- a/twilio/rest/api/v2010/account/new_key.py +++ b/twilio/rest/api/v2010/account/new_key.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,15 +76,12 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Keys.json".format(**self._solution) - def create( - self, friendly_name: Union[str, object] = values.unset - ) -> NewKeyInstance: + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: """ - Create the NewKeyInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - - :returns: The created NewKeyInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -93,23 +91,53 @@ def create( ) headers = values.of({"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, friendly_name: Union[str, object] = values.unset + ) -> NewKeyInstance: + """ + Create the NewKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewKeyInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return NewKeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: Union[str, object] = values.unset - ) -> NewKeyInstance: + ) -> ApiResponse: """ - Asynchronously create the NewKeyInstance + Create the NewKeyInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The created NewKeyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -119,14 +147,47 @@ async def create_async( ) headers = values.of({"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, friendly_name: Union[str, object] = values.unset + ) -> NewKeyInstance: + """ + Asynchronously create the NewKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewKeyInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return NewKeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the NewKeyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/api/v2010/account/new_signing_key.py b/twilio/rest/api/v2010/account/new_signing_key.py index bb9b0f2e2d..ebbb680958 100644 --- a/twilio/rest/api/v2010/account/new_signing_key.py +++ b/twilio/rest/api/v2010/account/new_signing_key.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,15 +76,12 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/SigningKeys.json".format(**self._solution) - def create( - self, friendly_name: Union[str, object] = values.unset - ) -> NewSigningKeyInstance: + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: """ - Create the NewSigningKeyInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - - :returns: The created NewSigningKeyInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -93,23 +91,53 @@ def create( ) headers = values.of({"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, friendly_name: Union[str, object] = values.unset + ) -> NewSigningKeyInstance: + """ + Create the NewSigningKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewSigningKeyInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return NewSigningKeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: Union[str, object] = values.unset - ) -> NewSigningKeyInstance: + ) -> ApiResponse: """ - Asynchronously create the NewSigningKeyInstance + Create the NewSigningKeyInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :returns: The created NewSigningKeyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -119,14 +147,47 @@ async def create_async( ) headers = values.of({"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, friendly_name: Union[str, object] = values.unset + ) -> NewSigningKeyInstance: + """ + Asynchronously create the NewSigningKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewSigningKeyInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return NewSigningKeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the NewSigningKeyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/api/v2010/account/notification.py b/twilio/rest/api/v2010/account/notification.py index 0a2e13da35..9afbd26354 100644 --- a/twilio/rest/api/v2010/account/notification.py +++ b/twilio/rest/api/v2010/account/notification.py @@ -15,6 +15,7 @@ from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -80,6 +81,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[NotificationContext] = None @property @@ -116,6 +118,24 @@ async def fetch_async(self) -> "NotificationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -147,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 @@ -154,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: """ @@ -174,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: """ @@ -205,6 +279,7 @@ def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: :param payload: Payload response from the API """ + return NotificationInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -316,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, @@ -343,6 +494,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( log=log, @@ -381,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( @@ -393,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, @@ -429,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, @@ -468,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: """ @@ -483,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: """ @@ -495,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 65ddfa1cdb..16f29c6f7d 100644 --- a/twilio/rest/api/v2010/account/outgoing_caller_id.py +++ b/twilio/rest/api/v2010/account/outgoing_caller_id.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,6 +59,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[OutgoingCallerIdContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OutgoingCallerIdInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OutgoingCallerIdInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "OutgoingCallerIdInstance": """ Fetch the OutgoingCallerIdInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "OutgoingCallerIdInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OutgoingCallerIdInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OutgoingCallerIdInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset ) -> "OutgoingCallerIdInstance": @@ -140,6 +178,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the OutgoingCallerIdInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OutgoingCallerIdInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -171,6 +237,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the OutgoingCallerIdInstance @@ -178,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: @@ -190,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: @@ -202,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: """ @@ -222,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, @@ -235,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" + + 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 + ) -> 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, @@ -264,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, @@ -293,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 @@ -311,6 +541,7 @@ def get_instance(self, payload: Dict[str, Any]) -> OutgoingCallerIdInstance: :param payload: Payload response from the API """ + return OutgoingCallerIdInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -410,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, @@ -433,6 +728,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( phone_number=phone_number, @@ -465,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( @@ -475,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, @@ -505,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, @@ -538,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: """ @@ -553,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: """ @@ -565,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 4031ba8196..dd8ca881f9 100644 --- a/twilio/rest/api/v2010/account/queue/__init__.py +++ b/twilio/rest/api/v2010/account/queue/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[QueueContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the QueueInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the QueueInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "QueueInstance": """ Fetch the QueueInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "QueueInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the QueueInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the QueueInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -157,6 +195,42 @@ async def update_async( max_size=max_size, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the QueueInstance with HTTP info + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + max_size=max_size, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the QueueInstance with HTTP info + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + max_size=max_size, + ) + @property def members(self) -> MemberList: """ @@ -195,6 +269,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._members: Optional[MemberList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the QueueInstance @@ -202,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: @@ -214,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: @@ -226,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: """ @@ -246,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 + 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. - :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: + 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, @@ -292,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" - 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, + 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, @@ -325,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: """ @@ -356,6 +610,7 @@ def get_instance(self, payload: Dict[str, Any]) -> QueueInstance: :param payload: Payload response from the API """ + return QueueInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -387,16 +642,14 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Queues.json".format(**self._solution) - def create( + def _create( self, friendly_name: str, max_size: Union[int, object] = values.unset - ) -> QueueInstance: + ) -> tuple: """ - Create the QueueInstance - - :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. - :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + Internal helper for create operation - :returns: The created QueueInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -407,24 +660,57 @@ def create( ) headers = values.of({"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, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> QueueInstance: + """ + Create the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The created QueueInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name, max_size=max_size) return QueueInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, max_size: Union[int, object] = values.unset - ) -> QueueInstance: + ) -> ApiResponse: """ - Asynchronously create the QueueInstance + Create the QueueInstance and return response metadata :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. - :returns: The created QueueInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, max_size=max_size + ) + instance = QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -435,14 +721,51 @@ async def create_async( ) headers = values.of({"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, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> QueueInstance: + """ + Asynchronously create the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The created QueueInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, max_size=max_size + ) return QueueInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the QueueInstance and return response metadata + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, max_size=max_size + ) + instance = QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -493,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, @@ -512,6 +885,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -538,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( @@ -546,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, @@ -570,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, @@ -597,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: """ @@ -612,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: """ @@ -624,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 bf092ff283..540befbbbe 100644 --- a/twilio/rest/api/v2010/account/queue/member.py +++ b/twilio/rest/api/v2010/account/queue/member.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( "queue_sid": queue_sid, "call_sid": call_sid or self.call_sid, } + self._context: Optional[MemberContext] = None @property @@ -93,6 +95,24 @@ async def fetch_async(self) -> "MemberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, url: str, method: Union[str, object] = values.unset ) -> "MemberInstance": @@ -125,6 +145,38 @@ async def update_async( method=method, ) + def update_with_http_info( + self, url: str, method: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP info + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + url=url, + method=method, + ) + + async def update_with_http_info_async( + self, url: str, method: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance with HTTP info + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + url=url, + method=method, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -162,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 @@ -169,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: """ @@ -190,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, @@ -204,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" - 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: 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, @@ -236,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, @@ -268,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 @@ -286,6 +462,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -374,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, @@ -393,6 +620,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -419,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( @@ -427,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, @@ -451,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, @@ -478,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: """ @@ -493,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: """ @@ -505,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 1766600ec3..75af476b00 100644 --- a/twilio/rest/api/v2010/account/recording/__init__.py +++ b/twilio/rest/api/v2010/account/recording/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,7 +58,7 @@ class Status(object): :ivar price: The one-time cost of creating the recording in the `price_unit` currency. :ivar price_unit: The currency used in the `price` property. Example: `USD`. :ivar status: - :ivar channels: The number of channels in the final recording file. Can be: `1` or `2`. + :ivar channels: The number of channels in the recording resource. For information on specifying the number of channels in the downloaded recording file, check out [Fetch a Recording’s media file](https://www.twilio.com/docs/voice/api/recording#download-dual-channel-media-file). :ivar source: :ivar error_code: The error code that describes why the recording is `absent`. The error code is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). This value is null if the recording `status` is not `absent`. :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. @@ -109,6 +110,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[RecordingContext] = None @property @@ -145,6 +147,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch( self, include_soft_deleted: Union[bool, object] = values.unset ) -> "RecordingInstance": @@ -173,6 +193,34 @@ async def fetch_async( include_soft_deleted=include_soft_deleted, ) + def fetch_with_http_info( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + include_soft_deleted=include_soft_deleted, + ) + + async def fetch_with_http_info_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + include_soft_deleted=include_soft_deleted, + ) + @property def add_on_results(self) -> AddOnResultList: """ @@ -221,6 +269,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._add_on_results: Optional[AddOnResultList] = None self._transcriptions: Optional[TranscriptionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RecordingInstance @@ -228,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: @@ -240,30 +324,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, include_soft_deleted: Union[bool, object] = values.unset - ) -> RecordingInstance: + async def delete_with_http_info_async(self) -> ApiResponse: """ - Fetch the RecordingInstance + Asynchronous coroutine that deletes the RecordingInstance and return response metadata - :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. - :returns: The fetched RecordingInstance + :returns: ApiResponse with success boolean, status code, and headers """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - data = values.of( + 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), } ) - 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, include_soft_deleted: Union[bool, object] = values.unset + ) -> RecordingInstance: + """ + Fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :returns: The fetched RecordingInstance + """ + payload, _, _ = self._fetch(include_soft_deleted=include_soft_deleted) return RecordingInstance( self._version, payload, @@ -271,27 +377,64 @@ def fetch( sid=self._solution["sid"], ) - async def fetch_async( + def fetch_with_http_info( self, include_soft_deleted: Union[bool, object] = values.unset - ) -> RecordingInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the RecordingInstance + Fetch the RecordingInstance and return response metadata :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. - :returns: The fetched RecordingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + include_soft_deleted=include_soft_deleted + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> tuple: """ + Internal async helper for fetch operation - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), } ) - 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, include_soft_deleted: Union[bool, object] = values.unset + ) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance + """ + payload, _, _ = await self._fetch_async( + include_soft_deleted=include_soft_deleted + ) return RecordingInstance( self._version, payload, @@ -299,6 +442,27 @@ async def fetch_async( sid=self._solution["sid"], ) + async def fetch_with_http_info_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance and return response metadata + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + include_soft_deleted=include_soft_deleted + ) + instance = RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def add_on_results(self) -> AddOnResultList: """ @@ -343,6 +507,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: :param payload: Payload response from the API """ + return RecordingInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -464,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, @@ -495,6 +748,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -539,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( @@ -553,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, @@ -595,8 +936,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, @@ -640,10 +987,120 @@ async def page_async( } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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: """ @@ -655,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: """ @@ -667,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 af1e75f4c6..2104ab225d 100644 --- a/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py +++ b/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def __init__( "reference_sid": reference_sid, "sid": sid or self.sid, } + self._context: Optional[AddOnResultContext] = None @property @@ -121,6 +123,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AddOnResultInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddOnResultInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AddOnResultInstance": """ Fetch the AddOnResultInstance @@ -139,6 +159,24 @@ async def fetch_async(self) -> "AddOnResultInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddOnResultInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AddOnResultInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def payloads(self) -> PayloadList: """ @@ -183,6 +221,20 @@ def __init__( self._payloads: Optional[PayloadList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AddOnResultInstance @@ -190,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: @@ -202,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: @@ -214,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: """ @@ -235,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: @@ -281,6 +419,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AddOnResultInstance: :param payload: Payload response from the API """ + return AddOnResultInstance( self._version, payload, @@ -369,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, @@ -388,6 +577,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -414,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( @@ -422,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, @@ -446,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, @@ -473,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: """ @@ -488,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: """ @@ -500,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 1dc26e1d7b..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 @@ -15,11 +15,13 @@ from datetime import datetime from typing import 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): @@ -74,6 +76,7 @@ def __init__( "add_on_result_sid": add_on_result_sid, "sid": sid or self.sid, } + self._context: Optional[PayloadContext] = None @property @@ -112,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 @@ -130,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 @@ -172,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 @@ -179,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: @@ -191,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: @@ -203,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"], @@ -217,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: """ @@ -225,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"], @@ -239,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: """ @@ -258,6 +423,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PayloadInstance: :param payload: Payload response from the API """ + return PayloadInstance( self._version, payload, @@ -355,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, @@ -374,6 +590,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -400,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( @@ -408,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, @@ -432,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, @@ -459,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: """ @@ -474,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: """ @@ -486,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 bb6e0e405a..166d49f641 100644 --- a/twilio/rest/api/v2010/account/recording/transcription.py +++ b/twilio/rest/api/v2010/account/recording/transcription.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -78,6 +79,7 @@ def __init__( "recording_sid": recording_sid, "sid": sid or self.sid, } + self._context: Optional[TranscriptionContext] = None @property @@ -115,6 +117,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TranscriptionInstance": """ Fetch the TranscriptionInstance @@ -133,6 +153,24 @@ async def fetch_async(self) -> "TranscriptionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -168,6 +206,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TranscriptionInstance @@ -175,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: @@ -187,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: @@ -199,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: """ @@ -220,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: """ @@ -252,6 +390,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: :param payload: Payload response from the API """ + return TranscriptionInstance( self._version, payload, @@ -340,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, @@ -359,6 +548,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -385,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( @@ -393,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, @@ -417,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, @@ -444,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: """ @@ -459,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: """ @@ -471,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 2af049a20b..c1c2e3f689 100644 --- a/twilio/rest/api/v2010/account/short_code.py +++ b/twilio/rest/api/v2010/account/short_code.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[ShortCodeContext] = None @property @@ -104,6 +106,24 @@ async def fetch_async(self) -> "ShortCodeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ShortCodeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ShortCodeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -164,6 +184,66 @@ async def update_async( sms_fallback_method=sms_fallback_method, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ShortCodeInstance with HTTP info + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ShortCodeInstance with HTTP info + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -195,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 @@ -202,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: """ @@ -222,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, @@ -243,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, @@ -266,13 +395,45 @@ def update( "SmsFallbackMethod": sms_fallback_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: 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, @@ -280,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, @@ -288,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`. @@ -299,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, @@ -311,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, @@ -325,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 @@ -343,6 +605,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: :param payload: Payload response from the API """ + return ShortCodeInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -442,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, @@ -465,6 +792,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -497,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( @@ -507,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, @@ -537,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, @@ -570,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: """ @@ -585,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: """ @@ -597,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 6ddc7b92b0..64ba733192 100644 --- a/twilio/rest/api/v2010/account/signing_key.py +++ b/twilio/rest/api/v2010/account/signing_key.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[SigningKeyContext] = None @property @@ -88,6 +90,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SigningKeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SigningKeyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SigningKeyInstance": """ Fetch the SigningKeyInstance @@ -106,6 +126,24 @@ async def fetch_async(self) -> "SigningKeyInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SigningKeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SigningKeyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset ) -> "SigningKeyInstance": @@ -134,6 +172,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the SigningKeyInstance with HTTP info + + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SigningKeyInstance with HTTP info + + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -165,6 +231,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SigningKeyInstance @@ -172,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: @@ -184,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: @@ -196,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: """ @@ -216,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, @@ -229,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({}) - 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 + ) -> SigningKeyInstance: + """ + Update the SigningKeyInstance + + :param friendly_name: + + :returns: The updated SigningKeyInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) return SigningKeyInstance( self._version, payload, @@ -258,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({}) - 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 + ) -> 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, @@ -287,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 @@ -305,6 +535,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SigningKeyInstance: :param payload: Payload response from the API """ + return SigningKeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -386,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, @@ -405,6 +686,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -431,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( @@ -439,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, @@ -463,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, @@ -490,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: """ @@ -505,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: """ @@ -517,7 +930,7 @@ async def get_page_async(self, target_url: str) -> SigningKeyPage: :returns: Page of SigningKeyInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SigningKeyPage(self._version, response, self._solution) + return SigningKeyPage(self._version, response, solution=self._solution) def get(self, sid: str) -> SigningKeyContext: """ diff --git a/twilio/rest/api/v2010/account/sip/credential_list/__init__.py b/twilio/rest/api/v2010/account/sip/credential_list/__init__.py index 30bb7094e7..0aef74f3b0 100644 --- a/twilio/rest/api/v2010/account/sip/credential_list/__init__.py +++ b/twilio/rest/api/v2010/account/sip/credential_list/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[CredentialListContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialListInstance": """ Fetch the CredentialListInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "CredentialListInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, friendly_name: str) -> "CredentialListInstance": """ Update the CredentialListInstance @@ -139,6 +177,30 @@ async def update_async(self, friendly_name: str) -> "CredentialListInstance": friendly_name=friendly_name, ) + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the CredentialListInstance with HTTP info + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialListInstance with HTTP info + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + @property def credentials(self) -> CredentialList: """ @@ -179,6 +241,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._credentials: Optional[CredentialList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialListInstance @@ -186,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: @@ -198,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: @@ -210,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: """ @@ -230,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, @@ -243,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({}) + + 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) -> 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, @@ -270,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, @@ -297,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: """ @@ -328,6 +548,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: :param payload: Payload response from the API """ + return CredentialListInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -361,13 +582,12 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) - def create(self, friendly_name: str) -> CredentialListInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the CredentialListInstance + 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( @@ -377,21 +597,47 @@ def create(self, friendly_name: str) -> CredentialListInstance: ) headers = values.of({"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, 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( @@ -401,14 +647,43 @@ async def create_async(self, friendly_name: str) -> CredentialListInstance: ) headers = values.of({"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, 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, @@ -459,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, @@ -478,6 +803,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -504,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( @@ -512,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, @@ -536,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, @@ -563,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: """ @@ -578,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: """ @@ -590,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 1e46bfe16e..2a237527f2 100644 --- a/twilio/rest/api/v2010/account/sip/credential_list/credential.py +++ b/twilio/rest/api/v2010/account/sip/credential_list/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( "credential_list_sid": credential_list_sid, "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, password: Union[str, object] = values.unset ) -> "CredentialInstance": @@ -143,6 +181,34 @@ async def update_async( password=password, ) + def update_with_http_info( + self, password: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + password=password, + ) + + async def update_with_http_info_async( + self, password: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + password=password, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -178,6 +244,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -185,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: @@ -197,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: @@ -209,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: """ @@ -230,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, @@ -244,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, @@ -272,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({}) + + 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, 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, @@ -302,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 @@ -320,6 +550,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: :param payload: Payload response from the API """ + return CredentialInstance( self._version, payload, @@ -358,14 +589,12 @@ def __init__(self, version: Version, account_sid: str, credential_list_sid: str) **self._solution ) - def create(self, username: str, password: str) -> CredentialInstance: + def _create(self, username: str, password: str) -> tuple: """ - Create the CredentialInstance + Internal helper for create operation - :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: + tuple: (payload, status_code, headers) """ data = values.of( @@ -376,10 +605,24 @@ def create(self, username: str, password: str) -> CredentialInstance: ) headers = values.of({"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, 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, @@ -387,14 +630,32 @@ def create(self, username: str, password: str) -> CredentialInstance: credential_list_sid=self._solution["credential_list_sid"], ) - async def create_async(self, username: str, password: str) -> CredentialInstance: + def create_with_http_info(self, username: str, password: str) -> ApiResponse: """ - Asynchronously create the CredentialInstance + Create the CredentialInstance and return response metadata :param username: The username that will be passed when authenticating SIP requests. The username should be sent in response to Twilio's challenge of the initial INVITE. It can be up to 32 characters long. :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) - :returns: The created CredentialInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + username=username, password=password + ) + instance = CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, username: str, password: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -405,10 +666,24 @@ async def create_async(self, username: str, password: str) -> CredentialInstance ) headers = values.of({"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, 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, @@ -416,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, @@ -466,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, @@ -485,6 +832,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -511,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( @@ -519,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, @@ -543,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, @@ -570,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: """ @@ -585,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: """ @@ -597,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 9ea7260438..3b8f3f32e9 100644 --- a/twilio/rest/api/v2010/account/sip/domain/__init__.py +++ b/twilio/rest/api/v2010/account/sip/domain/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -101,6 +102,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[DomainContext] = None @property @@ -137,6 +139,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DomainInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DomainInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "DomainInstance": """ Fetch the DomainInstance @@ -155,6 +175,24 @@ async def fetch_async(self) -> "DomainInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -257,6 +295,108 @@ async def update_async( emergency_caller_sid=emergency_caller_sid, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the DomainInstance with HTTP info + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainInstance with HTTP info + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + @property def auth(self) -> AuthTypesList: """ @@ -315,6 +455,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): IpAccessControlListMappingList ] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the DomainInstance @@ -322,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: @@ -334,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: @@ -346,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: """ @@ -366,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, @@ -394,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 + Internal helper for update operation - :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 + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -433,21 +659,17 @@ def update( "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, @@ -464,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`. @@ -482,32 +704,21 @@ async def update_async( :returns: The updated DomainInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "VoiceFallbackMethod": voice_fallback_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceMethod": voice_method, - "VoiceStatusCallbackMethod": voice_status_callback_method, - "VoiceStatusCallbackUrl": voice_status_callback_url, - "VoiceUrl": voice_url, - "SipRegistration": serialize.boolean_to_string(sip_registration), - "DomainName": domain_name, - "EmergencyCallingEnabled": serialize.boolean_to_string( - emergency_calling_enabled - ), - "Secure": serialize.boolean_to_string(secure), - "ByocTrunkSid": byoc_trunk_sid, - "EmergencyCallerSid": emergency_caller_sid, - } - ) - - 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, @@ -515,10 +726,235 @@ 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: + """ + 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( @@ -572,6 +1008,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DomainInstance: :param payload: Payload response from the API """ + return DomainInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -603,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, @@ -618,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. @@ -636,7 +1179,49 @@ def create( :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. - :returns: The created DomainInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + domain_name=domain_name, + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + voice_status_callback_url=voice_status_callback_url, + voice_status_callback_method=voice_status_callback_method, + sip_registration=sip_registration, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + instance = DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + domain_name: str, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -660,12 +1245,12 @@ def create( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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( @@ -703,35 +1288,79 @@ async def create_async( :returns: The created DomainInstance """ - - data = values.of( - { - "DomainName": domain_name, - "FriendlyName": friendly_name, - "VoiceUrl": voice_url, - "VoiceMethod": voice_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceFallbackMethod": voice_fallback_method, - "VoiceStatusCallbackUrl": voice_status_callback_url, - "VoiceStatusCallbackMethod": voice_status_callback_method, - "SipRegistration": serialize.boolean_to_string(sip_registration), - "EmergencyCallingEnabled": serialize.boolean_to_string( - emergency_calling_enabled - ), - "Secure": serialize.boolean_to_string(secure), - "ByocTrunkSid": byoc_trunk_sid, - "EmergencyCallerSid": emergency_caller_sid, - } + payload, _, _ = await self._create_async( + domain_name=domain_name, + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + voice_status_callback_url=voice_status_callback_url, + voice_status_callback_method=voice_status_callback_method, + sip_registration=sip_registration, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + 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, @@ -783,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, @@ -802,6 +1481,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -828,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( @@ -836,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, @@ -860,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, @@ -887,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: """ @@ -902,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: """ @@ -914,7 +1725,7 @@ async def get_page_async(self, target_url: str) -> DomainPage: :returns: Page of DomainInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DomainPage(self._version, response, self._solution) + return DomainPage(self._version, response, solution=self._solution) def get(self, sid: str) -> DomainContext: """ diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py index ff6fd5136e..0e539d09c6 100644 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[AuthCallsCredentialListMappingContext] = None @property @@ -93,6 +95,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthCallsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthCallsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AuthCallsCredentialListMappingInstance": """ Fetch the AuthCallsCredentialListMappingInstance @@ -111,6 +131,24 @@ async def fetch_async(self) -> "AuthCallsCredentialListMappingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthCallsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthCallsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -146,6 +184,20 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AuthCallsCredentialListMappingInstance @@ -153,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: @@ -165,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: @@ -177,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: """ @@ -198,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: """ @@ -234,6 +372,7 @@ def get_instance( :param payload: Payload response from the API """ + return AuthCallsCredentialListMappingInstance( self._version, payload, @@ -272,15 +411,12 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str): **self._solution ) - def create( - self, credential_list_sid: str - ) -> AuthCallsCredentialListMappingInstance: + def _create(self, credential_list_sid: str) -> tuple: """ - Create the AuthCallsCredentialListMappingInstance + Internal helper for create operation - :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. - - :returns: The created AuthCallsCredentialListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -290,10 +426,25 @@ def create( ) headers = values.of({"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, 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, @@ -301,15 +452,31 @@ def create( domain_sid=self._solution["domain_sid"], ) - async def create_async( - self, credential_list_sid: str - ) -> AuthCallsCredentialListMappingInstance: + def create_with_http_info(self, credential_list_sid: str) -> ApiResponse: """ - Asynchronously create the AuthCallsCredentialListMappingInstance + Create the AuthCallsCredentialListMappingInstance and return response metadata :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. - :returns: The created AuthCallsCredentialListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + credential_list_sid=credential_list_sid + ) + instance = AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, credential_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -319,10 +486,27 @@ async def create_async( ) headers = values.of({"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, 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, @@ -330,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, @@ -380,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, @@ -399,6 +654,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -425,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( @@ -433,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, @@ -457,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( @@ -486,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: """ @@ -504,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( @@ -520,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 82099164e7..d8a7aba9a7 100644 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[AuthCallsIpAccessControlListMappingContext] = None @property @@ -93,6 +95,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthCallsIpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthCallsIpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AuthCallsIpAccessControlListMappingInstance": """ Fetch the AuthCallsIpAccessControlListMappingInstance @@ -111,6 +131,24 @@ async def fetch_async(self) -> "AuthCallsIpAccessControlListMappingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthCallsIpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthCallsIpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -148,6 +186,20 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AuthCallsIpAccessControlListMappingInstance @@ -155,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: @@ -167,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: @@ -179,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: """ @@ -200,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: """ @@ -238,6 +376,7 @@ def get_instance( :param payload: Payload response from the API """ + return AuthCallsIpAccessControlListMappingInstance( self._version, payload, @@ -276,15 +415,12 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str): **self._solution ) - def create( - self, ip_access_control_list_sid: str - ) -> AuthCallsIpAccessControlListMappingInstance: + def _create(self, ip_access_control_list_sid: str) -> tuple: """ - Create the AuthCallsIpAccessControlListMappingInstance + Internal helper for create operation - :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. - - :returns: The created AuthCallsIpAccessControlListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -294,10 +430,27 @@ def create( ) headers = values.of({"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, 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, @@ -305,15 +458,31 @@ def create( domain_sid=self._solution["domain_sid"], ) - async def create_async( - self, ip_access_control_list_sid: str - ) -> AuthCallsIpAccessControlListMappingInstance: + def create_with_http_info(self, ip_access_control_list_sid: str) -> ApiResponse: """ - Asynchronously create the AuthCallsIpAccessControlListMappingInstance + Create the AuthCallsIpAccessControlListMappingInstance and return response metadata :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. - :returns: The created AuthCallsIpAccessControlListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ip_access_control_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -323,10 +492,27 @@ async def create_async( ) headers = values.of({"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, 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, @@ -334,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, @@ -384,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, @@ -403,6 +660,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -429,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( @@ -437,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, @@ -461,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( @@ -490,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: """ @@ -508,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( @@ -524,7 +917,7 @@ async def get_page_async( """ response = await self._version.domain.twilio.request_async("GET", target_url) return AuthCallsIpAccessControlListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) def get(self, sid: str) -> AuthCallsIpAccessControlListMappingContext: diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py index 22acb7ef10..78671458dc 100644 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[AuthRegistrationsCredentialListMappingContext] = None @property @@ -93,6 +95,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthRegistrationsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthRegistrationsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AuthRegistrationsCredentialListMappingInstance": """ Fetch the AuthRegistrationsCredentialListMappingInstance @@ -111,6 +131,24 @@ async def fetch_async(self) -> "AuthRegistrationsCredentialListMappingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthRegistrationsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthRegistrationsCredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -146,6 +184,20 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AuthRegistrationsCredentialListMappingInstance @@ -153,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: @@ -165,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: @@ -177,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: """ @@ -198,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: """ @@ -234,6 +372,7 @@ def get_instance( :param payload: Payload response from the API """ + return AuthRegistrationsCredentialListMappingInstance( self._version, payload, @@ -272,15 +411,12 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str): **self._solution ) - def create( - self, credential_list_sid: str - ) -> AuthRegistrationsCredentialListMappingInstance: + def _create(self, credential_list_sid: str) -> tuple: """ - Create the AuthRegistrationsCredentialListMappingInstance + Internal helper for create operation - :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. - - :returns: The created AuthRegistrationsCredentialListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -290,10 +426,25 @@ def create( ) headers = values.of({"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, 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, @@ -301,15 +452,31 @@ def create( domain_sid=self._solution["domain_sid"], ) - async def create_async( - self, credential_list_sid: str - ) -> AuthRegistrationsCredentialListMappingInstance: + def create_with_http_info(self, credential_list_sid: str) -> ApiResponse: """ - Asynchronously create the AuthRegistrationsCredentialListMappingInstance + Create the AuthRegistrationsCredentialListMappingInstance and return response metadata :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. - :returns: The created AuthRegistrationsCredentialListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + credential_list_sid=credential_list_sid + ) + instance = AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, credential_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -319,10 +486,27 @@ async def create_async( ) headers = values.of({"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, 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, @@ -330,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, @@ -380,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, @@ -399,6 +654,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -425,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( @@ -433,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, @@ -457,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( @@ -486,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: """ @@ -504,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( @@ -520,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 e20e08e0fb..cbdbc3e470 100644 --- a/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py +++ b/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[CredentialListMappingContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialListMappingInstance": """ Fetch the CredentialListMappingInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "CredentialListMappingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -148,6 +186,20 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialListMappingInstance @@ -155,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: @@ -167,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: @@ -179,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: """ @@ -200,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: """ @@ -232,6 +370,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialListMappingInstance :param payload: Payload response from the API """ + return CredentialListMappingInstance( self._version, payload, @@ -270,13 +409,12 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str): **self._solution ) - def create(self, credential_list_sid: str) -> CredentialListMappingInstance: + def _create(self, credential_list_sid: str) -> tuple: """ - Create the CredentialListMappingInstance + 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( @@ -286,10 +424,23 @@ def create(self, credential_list_sid: str) -> CredentialListMappingInstance: ) headers = values.of({"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, 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, @@ -297,15 +448,31 @@ def create(self, credential_list_sid: str) -> CredentialListMappingInstance: domain_sid=self._solution["domain_sid"], ) - async def create_async( - self, credential_list_sid: str - ) -> CredentialListMappingInstance: + def create_with_http_info(self, credential_list_sid: str) -> ApiResponse: """ - Asynchronously create the CredentialListMappingInstance + Create the CredentialListMappingInstance and return response metadata :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. - :returns: The created CredentialListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + credential_list_sid=credential_list_sid + ) + instance = CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, credential_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -315,10 +482,27 @@ async def create_async( ) headers = values.of({"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, 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, @@ -326,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, @@ -376,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, @@ -395,6 +650,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -421,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( @@ -429,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, @@ -453,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, @@ -480,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 + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_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, + } ) - return CredentialListMappingPage(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 = 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: """ @@ -495,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: """ @@ -507,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 607bb6ce12..2a3c582b70 100644 --- a/twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py +++ b/twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[IpAccessControlListMappingContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "IpAccessControlListMappingInstance": """ Fetch the IpAccessControlListMappingInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "IpAccessControlListMappingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -150,6 +188,20 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the IpAccessControlListMappingInstance @@ -157,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: @@ -169,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: @@ -181,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: """ @@ -202,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: """ @@ -236,6 +374,7 @@ def get_instance( :param payload: Payload response from the API """ + return IpAccessControlListMappingInstance( self._version, payload, @@ -274,15 +413,12 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str): **self._solution ) - def create( - self, ip_access_control_list_sid: str - ) -> IpAccessControlListMappingInstance: + def _create(self, ip_access_control_list_sid: str) -> tuple: """ - Create the IpAccessControlListMappingInstance + 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( @@ -292,10 +428,27 @@ def create( ) headers = values.of({"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, 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, @@ -303,15 +456,31 @@ def create( domain_sid=self._solution["domain_sid"], ) - async def create_async( - self, ip_access_control_list_sid: str - ) -> IpAccessControlListMappingInstance: + def create_with_http_info(self, ip_access_control_list_sid: str) -> ApiResponse: """ - Asynchronously create the IpAccessControlListMappingInstance + Create the IpAccessControlListMappingInstance and return response metadata :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. - :returns: The created IpAccessControlListMappingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ip_access_control_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -321,10 +490,27 @@ async def create_async( ) headers = values.of({"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, 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, @@ -332,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, @@ -382,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, @@ -401,6 +658,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -427,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( @@ -435,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, @@ -459,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, @@ -486,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 ) - return IpAccessControlListMappingPage(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 IpAccessControlListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = IpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with IpAccessControlListMappingPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = IpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> IpAccessControlListMappingPage: """ @@ -501,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: """ @@ -513,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 cf75721a96..e2161d40ae 100644 --- a/twilio/rest/api/v2010/account/sip/ip_access_control_list/__init__.py +++ b/twilio/rest/api/v2010/account/sip/ip_access_control_list/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -63,6 +64,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[IpAccessControlListContext] = None @property @@ -99,6 +101,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "IpAccessControlListInstance": """ Fetch the IpAccessControlListInstance @@ -117,6 +137,24 @@ async def fetch_async(self) -> "IpAccessControlListInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, friendly_name: str) -> "IpAccessControlListInstance": """ Update the IpAccessControlListInstance @@ -141,6 +179,30 @@ async def update_async(self, friendly_name: str) -> "IpAccessControlListInstance friendly_name=friendly_name, ) + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the IpAccessControlListInstance with HTTP info + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the IpAccessControlListInstance with HTTP info + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + @property def ip_addresses(self) -> IpAddressList: """ @@ -183,6 +245,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._ip_addresses: Optional[IpAddressList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the IpAccessControlListInstance @@ -190,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: @@ -202,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: @@ -214,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: """ @@ -234,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, @@ -247,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({}) + + 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) -> 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, @@ -274,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, @@ -301,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: """ @@ -332,6 +552,7 @@ def get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: :param payload: Payload response from the API """ + return IpAccessControlListInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -365,13 +586,12 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) - def create(self, friendly_name: str) -> IpAccessControlListInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the IpAccessControlListInstance + 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( @@ -381,21 +601,47 @@ def create(self, friendly_name: str) -> IpAccessControlListInstance: ) headers = values.of({"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, 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( @@ -405,14 +651,43 @@ async def create_async(self, friendly_name: str) -> IpAccessControlListInstance: ) headers = values.of({"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, 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, @@ -463,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, @@ -482,6 +807,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -508,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( @@ -516,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, @@ -540,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, @@ -567,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: """ @@ -582,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: """ @@ -594,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 106bd7400e..aefcad2b39 100644 --- a/twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py +++ b/twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def __init__( "ip_access_control_list_sid": ip_access_control_list_sid, "sid": sid or self.sid, } + self._context: Optional[IpAddressContext] = None @property @@ -105,6 +107,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAddressInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAddressInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "IpAddressInstance": """ Fetch the IpAddressInstance @@ -123,6 +143,24 @@ async def fetch_async(self) -> "IpAddressInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAddressInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAddressInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, ip_address: Union[str, object] = values.unset, @@ -165,6 +203,48 @@ async def update_async( cidr_prefix_length=cidr_prefix_length, ) + def update_with_http_info( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the IpAddressInstance with HTTP info + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + + async def update_with_http_info_async( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IpAddressInstance with HTTP info + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -204,6 +284,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the IpAddressInstance @@ -211,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: @@ -223,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: @@ -235,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: """ @@ -256,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, @@ -292,13 +470,36 @@ def update( "CidrPrefixLength": cidr_prefix_length, } ) + 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, + 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, @@ -307,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, @@ -329,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, @@ -344,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 @@ -362,6 +642,7 @@ def get_instance(self, payload: Dict[str, Any]) -> IpAddressInstance: :param payload: Payload response from the API """ + return IpAddressInstance( self._version, payload, @@ -402,20 +683,17 @@ def __init__( **self._solution ) - def create( + def _create( self, friendly_name: str, ip_address: str, cidr_prefix_length: Union[int, object] = values.unset, - ) -> IpAddressInstance: + ) -> tuple: """ - Create the IpAddressInstance + Internal helper for create operation - :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: + tuple: (payload, status_code, headers) """ data = values.of( @@ -427,10 +705,34 @@ def create( ) headers = values.of({"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, + 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, @@ -438,20 +740,45 @@ def create( ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], ) - async def create_async( + def create_with_http_info( self, friendly_name: str, ip_address: str, cidr_prefix_length: Union[int, object] = values.unset, - ) -> IpAddressInstance: + ) -> ApiResponse: """ - Asynchronously create the IpAddressInstance + Create the IpAddressInstance and return response metadata :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. - :returns: The created IpAddressInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + ip_address=ip_address, + cidr_prefix_length=cidr_prefix_length, + ) + instance = IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -463,10 +790,34 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -474,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, @@ -524,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, @@ -543,6 +972,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -569,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( @@ -577,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, @@ -601,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, @@ -628,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: """ @@ -643,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: """ @@ -655,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 6d5edcf3e8..4cc10f7026 100644 --- a/twilio/rest/api/v2010/account/token.py +++ b/twilio/rest/api/v2010/account/token.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,13 +80,12 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Tokens.json".format(**self._solution) - def create(self, ttl: Union[int, object] = values.unset) -> TokenInstance: + def _create(self, ttl: Union[int, object] = values.unset) -> tuple: """ - Create the TokenInstance - - :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). + Internal helper for create operation - :returns: The created TokenInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -95,23 +95,49 @@ def create(self, ttl: Union[int, object] = values.unset) -> TokenInstance: ) headers = values.of({"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, 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( @@ -121,14 +147,45 @@ async def create_async( ) headers = values.of({"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, 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 a77bc42fb4..341c4ffdb3 100644 --- a/twilio/rest/api/v2010/account/transcription.py +++ b/twilio/rest/api/v2010/account/transcription.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[TranscriptionContext] = None @property @@ -112,6 +114,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TranscriptionInstance": """ Fetch the TranscriptionInstance @@ -130,6 +150,24 @@ async def fetch_async(self) -> "TranscriptionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -161,6 +199,20 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TranscriptionInstance @@ -168,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: @@ -180,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: @@ -192,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: """ @@ -212,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: """ @@ -243,6 +379,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: :param payload: Payload response from the API """ + return TranscriptionInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -326,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, @@ -345,6 +532,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -371,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( @@ -379,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, @@ -403,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, @@ -430,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: """ @@ -445,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: """ @@ -457,7 +776,7 @@ async def get_page_async(self, target_url: str) -> TranscriptionPage: :returns: Page of TranscriptionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return TranscriptionPage(self._version, response, self._solution) + return TranscriptionPage(self._version, response, solution=self._solution) def get(self, sid: str) -> TranscriptionContext: """ diff --git a/twilio/rest/api/v2010/account/usage/record/__init__.py b/twilio/rest/api/v2010/account/usage/record/__init__.py index 0afc8e3472..a721a595d3 100644 --- a/twilio/rest/api/v2010/account/usage/record/__init__.py +++ b/twilio/rest/api/v2010/account/usage/record/__init__.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,335 +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" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -379,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") @@ -420,6 +97,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RecordInstance: :param payload: Payload response from the API """ + return RecordInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -464,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, @@ -477,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. @@ -503,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, @@ -516,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. @@ -540,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, @@ -554,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. @@ -567,6 +321,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -580,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, @@ -592,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. @@ -605,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( @@ -617,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, @@ -653,12 +483,18 @@ def page( } ) - 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, @@ -692,10 +528,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 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: """ @@ -707,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: """ @@ -719,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 7c0b6f5ce4..3d01ff38a2 100644 --- a/twilio/rest/api/v2010/account/usage/record/all_time.py +++ b/twilio/rest/api/v2010/account/usage/record/all_time.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,335 +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" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -371,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") @@ -412,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AllTimeInstance: :param payload: Payload response from the API """ + return AllTimeInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -447,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, @@ -460,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. @@ -486,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, @@ -499,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. @@ -523,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, @@ -537,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. @@ -550,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -563,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, @@ -575,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. @@ -588,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( @@ -600,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, @@ -636,12 +466,18 @@ def page( } ) - 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, @@ -675,10 +511,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 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: """ @@ -690,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: """ @@ -702,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 a0acd62b2a..0be683fb86 100644 --- a/twilio/rest/api/v2010/account/usage/record/daily.py +++ b/twilio/rest/api/v2010/account/usage/record/daily.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,335 +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" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -371,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") @@ -412,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DailyInstance: :param payload: Payload response from the API """ + return DailyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -447,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, @@ -460,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. @@ -486,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, @@ -499,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. @@ -523,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, @@ -537,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. @@ -550,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -563,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, @@ -575,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. @@ -588,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( @@ -600,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, @@ -636,12 +466,18 @@ def page( } ) - 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, @@ -675,10 +511,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 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: """ @@ -690,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: """ @@ -702,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 21fa1e1b61..25cc8a5ce1 100644 --- a/twilio/rest/api/v2010/account/usage/record/last_month.py +++ b/twilio/rest/api/v2010/account/usage/record/last_month.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,335 +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" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -371,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") @@ -412,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> LastMonthInstance: :param payload: Payload response from the API """ + return LastMonthInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -447,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, @@ -460,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. @@ -486,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, @@ -499,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. @@ -523,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, @@ -537,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. @@ -550,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -563,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, @@ -575,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. @@ -588,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( @@ -600,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, @@ -636,12 +466,18 @@ def page( } ) - 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, @@ -675,10 +511,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 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: """ @@ -690,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: """ @@ -702,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 0eff14396a..9d597023be 100644 --- a/twilio/rest/api/v2010/account/usage/record/monthly.py +++ b/twilio/rest/api/v2010/account/usage/record/monthly.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,335 +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" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -371,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") @@ -412,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MonthlyInstance: :param payload: Payload response from the API """ + return MonthlyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -447,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, @@ -460,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. @@ -486,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, @@ -499,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. @@ -523,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, @@ -537,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. @@ -550,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -563,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, @@ -575,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. @@ -588,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( @@ -600,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, @@ -636,12 +466,18 @@ def page( } ) - 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, @@ -675,10 +511,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 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: """ @@ -690,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: """ @@ -702,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 646b4a49d5..b1f11399bd 100644 --- a/twilio/rest/api/v2010/account/usage/record/this_month.py +++ b/twilio/rest/api/v2010/account/usage/record/this_month.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,335 +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" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -371,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") @@ -412,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ThisMonthInstance: :param payload: Payload response from the API """ + return ThisMonthInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -447,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, @@ -460,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. @@ -486,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, @@ -499,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. @@ -523,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, @@ -537,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. @@ -550,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -563,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, @@ -575,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. @@ -588,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( @@ -600,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, @@ -636,12 +466,18 @@ def page( } ) - 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, @@ -675,10 +511,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 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: """ @@ -690,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: """ @@ -702,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 30de9d4cb7..dfe2e1fca4 100644 --- a/twilio/rest/api/v2010/account/usage/record/today.py +++ b/twilio/rest/api/v2010/account/usage/record/today.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,335 +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" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -371,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") @@ -412,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TodayInstance: :param payload: Payload response from the API """ + return TodayInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -447,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, @@ -460,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. @@ -486,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, @@ -499,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. @@ -523,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, @@ -537,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. @@ -550,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -563,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, @@ -575,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. @@ -588,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( @@ -600,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, @@ -636,12 +466,18 @@ def page( } ) - 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, @@ -675,10 +511,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 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: """ @@ -690,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: """ @@ -702,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 fbe9dd1f6f..24812d72a3 100644 --- a/twilio/rest/api/v2010/account/usage/record/yearly.py +++ b/twilio/rest/api/v2010/account/usage/record/yearly.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,335 +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" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -371,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") @@ -412,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> YearlyInstance: :param payload: Payload response from the API """ + return YearlyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -447,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, @@ -460,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. @@ -486,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, @@ -499,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. @@ -523,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, @@ -537,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. @@ -550,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -563,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, @@ -575,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. @@ -588,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( @@ -600,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, @@ -636,12 +466,18 @@ def page( } ) - 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, @@ -675,10 +511,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 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: """ @@ -690,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: """ @@ -702,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 db5f9eb472..32ad22f8d0 100644 --- a/twilio/rest/api/v2010/account/usage/record/yesterday.py +++ b/twilio/rest/api/v2010/account/usage/record/yesterday.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,335 +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" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. :ivar api_version: The API version used to create the resource. :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT - :ivar category: + :ivar category: The category of usage. For more information, see [Usage Categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). :ivar count: The number of usage events, such as the number of calls. :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. :ivar description: A plain-language description of the usage category. @@ -371,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") @@ -412,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> YesterdayInstance: :param payload: Payload response from the API """ + return YesterdayInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -447,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, @@ -460,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. @@ -486,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, @@ -499,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. @@ -523,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, @@ -537,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. @@ -550,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -563,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, @@ -575,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. @@ -588,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( @@ -600,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, @@ -636,12 +466,18 @@ def page( } ) - 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, @@ -675,10 +511,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 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: """ @@ -690,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: """ @@ -702,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 c3a1b241ca..8e975e0204 100644 --- a/twilio/rest/api/v2010/account/usage/trigger.py +++ b/twilio/rest/api/v2010/account/usage/trigger.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -35,329 +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" - TTS_GOOGLE = "tts-google" - TURNMEGABYTES = "turnmegabytes" - TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" - TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" - TURNMEGABYTES_GERMANY = "turnmegabytes-germany" - TURNMEGABYTES_INDIA = "turnmegabytes-india" - TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" - TURNMEGABYTES_JAPAN = "turnmegabytes-japan" - TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" - TURNMEGABYTES_USEAST = "turnmegabytes-useast" - TURNMEGABYTES_USWEST = "turnmegabytes-uswest" - TWILIO_INTERCONNECT = "twilio-interconnect" - VERIFY_PUSH = "verify-push" - VERIFY_TOTP = "verify-totp" - VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( - "verify-whatsapp-conversations-business-initiated" - ) - VIDEO_RECORDINGS = "video-recordings" - VIRTUAL_AGENT = "virtual-agent" - VOICE_INSIGHTS = "voice-insights" - VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-client-insights-on-demand-minute" - ) - VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-ptsn-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-interface-insights-on-demand-minute" - ) - VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( - "voice-insights-sip-trunking-insights-on-demand-minute" - ) - VOICE_INTELLIGENCE = "voice-intelligence" - VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" - VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" - WIRELESS = "wireless" - WIRELESS_ORDERS = "wireless-orders" - WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" - WIRELESS_ORDERS_BULK = "wireless-orders-bulk" - WIRELESS_ORDERS_ESIM = "wireless-orders-esim" - WIRELESS_ORDERS_STARTER = "wireless-orders-starter" - WIRELESS_USAGE = "wireless-usage" - WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" - WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" - WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" - WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-commands-centralandsouthamerica" - ) - WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" - WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" - WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" - WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" - WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" - WIRELESS_USAGE_DATA = "wireless-usage-data" - WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" - WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" - WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( - "wireless-usage-data-centralandsouthamerica" - ) - WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( - "wireless-usage-data-custom-additionalmb" - ) - WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" - WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" - WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" - WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( - "wireless-usage-data-individual-additionalgb" - ) - WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( - "wireless-usage-data-individual-firstgb" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( - "wireless-usage-data-international-roaming-canada" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( - "wireless-usage-data-international-roaming-india" - ) - WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( - "wireless-usage-data-international-roaming-mexico" - ) - WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" - WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" - WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" - WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" - WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" - WIRELESS_USAGE_MRC = "wireless-usage-mrc" - WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" - WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" - WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" - WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" - WIRELESS_USAGE_SMS = "wireless-usage-sms" - WIRELESS_USAGE_VOICE = "wireless-usage-voice" - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the trigger monitors. :ivar api_version: The API version used to create the resource. @@ -373,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`. """ @@ -408,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 @@ -453,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 @@ -471,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, @@ -513,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 @@ -544,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 @@ -551,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: @@ -563,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: @@ -575,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: """ @@ -595,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, @@ -630,13 +481,36 @@ 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, + 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, @@ -644,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, @@ -666,13 +566,36 @@ async def update_async( "FriendlyName": friendly_name, } ) + 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, + 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, @@ -680,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 @@ -698,6 +649,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TriggerInstance: :param payload: Payload response from the API """ + return TriggerInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -731,28 +683,21 @@ 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( @@ -768,36 +713,102 @@ def create( ) headers = values.of({"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, + 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( @@ -813,19 +824,92 @@ async def create_async( ) headers = values.of({"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, + 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]: @@ -837,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 @@ -861,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]: @@ -873,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 @@ -893,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]: @@ -908,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 @@ -918,6 +1072,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( recurring=recurring, @@ -932,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]: @@ -943,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 @@ -953,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( @@ -964,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, @@ -997,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, @@ -1033,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: """ @@ -1048,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: """ @@ -1060,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 261322712f..9594e19cc1 100644 --- a/twilio/rest/api/v2010/account/validation_request.py +++ b/twilio/rest/api/v2010/account/validation_request.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,7 +73,7 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) - def create( + def _create( self, phone_number: str, friendly_name: Union[str, object] = values.unset, @@ -80,18 +81,12 @@ def create( extension: Union[str, object] = values.unset, status_callback: Union[str, object] = values.unset, status_callback_method: Union[str, object] = values.unset, - ) -> ValidationRequestInstance: + ) -> tuple: """ - Create the ValidationRequestInstance + Internal helper for create operation - :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. - :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. - :param call_delay: The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. - :param extension: The digits to dial after connecting the verification call. - :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. - - :returns: The created ValidationRequestInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -106,15 +101,48 @@ def create( ) headers = values.of({"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, + phone_number: str, + friendly_name: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + extension: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ValidationRequestInstance: + """ + Create the ValidationRequestInstance + + :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. + :param call_delay: The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. + :param extension: The digits to dial after connecting the verification call. + :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. + + :returns: The created ValidationRequestInstance + """ + payload, _, _ = self._create( + phone_number=phone_number, + friendly_name=friendly_name, + call_delay=call_delay, + extension=extension, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) return ValidationRequestInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, phone_number: str, friendly_name: Union[str, object] = values.unset, @@ -122,9 +150,9 @@ async def create_async( extension: Union[str, object] = values.unset, status_callback: Union[str, object] = values.unset, status_callback_method: Union[str, object] = values.unset, - ) -> ValidationRequestInstance: + ) -> ApiResponse: """ - Asynchronously create the ValidationRequestInstance + Create the ValidationRequestInstance and return response metadata :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. @@ -133,7 +161,35 @@ async def create_async( :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. - :returns: The created ValidationRequestInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + friendly_name=friendly_name, + call_delay=call_delay, + extension=extension, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + instance = ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + phone_number: str, + friendly_name: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + extension: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -148,14 +204,81 @@ async def create_async( ) headers = values.of({"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, + phone_number: str, + friendly_name: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + extension: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ValidationRequestInstance: + """ + Asynchronously create the ValidationRequestInstance + + :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. + :param call_delay: The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. + :param extension: The digits to dial after connecting the verification call. + :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. + + :returns: The created ValidationRequestInstance + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + friendly_name=friendly_name, + call_delay=call_delay, + extension=extension, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) return ValidationRequestInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, + phone_number: str, + friendly_name: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + extension: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ValidationRequestInstance and return response metadata + + :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. + :param call_delay: The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. + :param extension: The digits to dial after connecting the verification call. + :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + friendly_name=friendly_name, + call_delay=call_delay, + extension=extension, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + instance = ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/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 e8c874b920..a9c9e9afcd 100644 --- a/twilio/rest/microvisor/MicrovisorBase.py +++ b/twilio/rest/assistants/AssistantsBase.py @@ -13,24 +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) @@ -41,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/bulkexports/v1/export/__init__.py b/twilio/rest/bulkexports/v1/export/__init__.py index c5c11df086..2bb449d2a4 100644 --- a/twilio/rest/bulkexports/v1/export/__init__.py +++ b/twilio/rest/bulkexports/v1/export/__init__.py @@ -13,6 +13,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 @@ -45,6 +47,7 @@ def __init__( self._solution = { "resource_type": resource_type or self.resource_type, } + self._context: Optional[ExportContext] = None @property @@ -80,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: """ @@ -124,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 @@ -131,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: """ @@ -150,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: diff --git a/twilio/rest/bulkexports/v1/export/day.py b/twilio/rest/bulkexports/v1/export/day.py index fcbc56e979..b19395fde5 100644 --- a/twilio/rest/bulkexports/v1/export/day.py +++ b/twilio/rest/bulkexports/v1/export/day.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( "resource_type": resource_type, "day": day or self.day, } + self._context: Optional[DayContext] = None @property @@ -87,6 +89,24 @@ async def fetch_async(self) -> "DayInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DayInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DayInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -116,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 @@ -123,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: """ @@ -143,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: """ @@ -174,6 +248,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DayInstance: :param payload: Payload response from the API """ + return DayInstance( self._version, payload, resource_type=self._solution["resource_type"] ) @@ -255,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, @@ -274,6 +399,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -300,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( @@ -308,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, @@ -332,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, @@ -359,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: """ @@ -374,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: """ @@ -386,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 9a81fb23cb..dee11094c1 100644 --- a/twilio/rest/bulkexports/v1/export/export_custom_job.py +++ b/twilio/rest/bulkexports/v1/export/export_custom_job.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -47,7 +48,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], resource_type: str self.webhook_method: Optional[str] = payload.get("webhook_method") self.email: Optional[str] = payload.get("email") self.job_sid: Optional[str] = payload.get("job_sid") - self.details: Optional[Dict[str, object]] = payload.get("details") + self.details: Optional[List[Dict[str, object]]] = payload.get("details") self.job_queue_position: Optional[str] = payload.get("job_queue_position") self.estimated_completion_time: Optional[str] = payload.get( "estimated_completion_time" @@ -75,6 +76,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ExportCustomJobInstance: :param payload: Payload response from the API """ + return ExportCustomJobInstance( self._version, payload, resource_type=self._solution["resource_type"] ) @@ -106,7 +108,7 @@ def __init__(self, version: Version, resource_type: str): } self._uri = "/Exports/{resource_type}/Jobs".format(**self._solution) - def create( + def _create( self, start_day: str, end_day: str, @@ -114,18 +116,12 @@ def create( webhook_url: Union[str, object] = values.unset, webhook_method: Union[str, object] = values.unset, email: Union[str, object] = values.unset, - ) -> ExportCustomJobInstance: + ) -> tuple: """ - Create the ExportCustomJobInstance + Internal helper for create operation - :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd - :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. - :param friendly_name: The friendly name specified when creating the job - :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. - :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. - :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. - - :returns: The created ExportCustomJobInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -140,15 +136,48 @@ def create( ) headers = values.of({"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, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ExportCustomJobInstance: + """ + Create the ExportCustomJobInstance + + :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd + :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. + :param friendly_name: The friendly name specified when creating the job + :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. + :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. + + :returns: The created ExportCustomJobInstance + """ + payload, _, _ = self._create( + start_day=start_day, + end_day=end_day, + friendly_name=friendly_name, + webhook_url=webhook_url, + webhook_method=webhook_method, + email=email, + ) return ExportCustomJobInstance( self._version, payload, resource_type=self._solution["resource_type"] ) - async def create_async( + def create_with_http_info( self, start_day: str, end_day: str, @@ -156,9 +185,9 @@ async def create_async( webhook_url: Union[str, object] = values.unset, webhook_method: Union[str, object] = values.unset, email: Union[str, object] = values.unset, - ) -> ExportCustomJobInstance: + ) -> ApiResponse: """ - Asynchronously create the ExportCustomJobInstance + Create the ExportCustomJobInstance and return response metadata :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. @@ -167,7 +196,35 @@ async def create_async( :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. - :returns: The created ExportCustomJobInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + start_day=start_day, + end_day=end_day, + friendly_name=friendly_name, + webhook_url=webhook_url, + webhook_method=webhook_method, + email=email, + ) + instance = ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -182,14 +239,81 @@ async def create_async( ) headers = values.of({"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, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ExportCustomJobInstance: + """ + Asynchronously create the ExportCustomJobInstance + + :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd + :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. + :param friendly_name: The friendly name specified when creating the job + :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. + :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. + + :returns: The created ExportCustomJobInstance + """ + payload, _, _ = await self._create_async( + start_day=start_day, + end_day=end_day, + friendly_name=friendly_name, + webhook_url=webhook_url, + webhook_method=webhook_method, + email=email, + ) return ExportCustomJobInstance( self._version, payload, resource_type=self._solution["resource_type"] ) + async def create_with_http_info_async( + self, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ExportCustomJobInstance and return response metadata + + :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd + :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. + :param friendly_name: The friendly name specified when creating the job + :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. + :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + start_day=start_day, + end_day=end_day, + friendly_name=friendly_name, + webhook_url=webhook_url, + webhook_method=webhook_method, + email=email, + ) + instance = ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -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 48b2df1ab3..2f8a7ef8f9 100644 --- a/twilio/rest/bulkexports/v1/export/job.py +++ b/twilio/rest/bulkexports/v1/export/job.py @@ -12,7 +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 @@ -42,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") @@ -58,6 +60,7 @@ def __init__( self._solution = { "job_sid": job_sid or self.job_sid, } + self._context: Optional[JobContext] = None @property @@ -93,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 @@ -111,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 @@ -138,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 @@ -145,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: @@ -157,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: @@ -169,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: """ @@ -188,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: """ diff --git a/twilio/rest/bulkexports/v1/export_configuration.py b/twilio/rest/bulkexports/v1/export_configuration.py index c6629d21cf..d5b684b092 100644 --- a/twilio/rest/bulkexports/v1/export_configuration.py +++ b/twilio/rest/bulkexports/v1/export_configuration.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -46,6 +47,7 @@ def __init__( self._solution = { "resource_type": resource_type or self.resource_type, } + self._context: Optional[ExportConfigurationContext] = None @property @@ -81,6 +83,24 @@ async def fetch_async(self) -> "ExportConfigurationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExportConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExportConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, enabled: Union[bool, object] = values.unset, @@ -123,6 +143,48 @@ async def update_async( webhook_method=webhook_method, ) + def update_with_http_info( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ExportConfigurationInstance with HTTP info + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + enabled=enabled, + webhook_url=webhook_url, + webhook_method=webhook_method, + ) + + async def update_with_http_info_async( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ExportConfigurationInstance with HTTP info + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + enabled=enabled, + webhook_url=webhook_url, + webhook_method=webhook_method, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -150,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 @@ -157,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: """ @@ -176,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, @@ -203,6 +347,49 @@ 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": serialize.boolean_to_string(enabled), @@ -210,15 +397,14 @@ def update( "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( @@ -236,23 +422,35 @@ async def update_async( :returns: The updated ExportConfigurationInstance """ - data = values.of( - { - "Enabled": serialize.boolean_to_string(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: """ diff --git a/twilio/rest/chat/v1/credential.py b/twilio/rest/chat/v1/credential.py index 6bb8b3f981..a5d48dc68b 100644 --- a/twilio/rest/chat/v1/credential.py +++ b/twilio/rest/chat/v1/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -174,6 +212,66 @@ async def update_async( secret=secret, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,6 +299,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -208,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: @@ -220,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: @@ -232,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: """ @@ -251,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, @@ -284,6 +514,64 @@ 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, @@ -294,14 +582,15 @@ def update( "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, @@ -324,24 +613,47 @@ async def update_async( :returns: The updated CredentialInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": serialize.boolean_to_string(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: """ @@ -361,6 +673,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: :param payload: Payload response from the API """ + return CredentialInstance(self._version, payload) def __repr__(self) -> str: @@ -385,7 +698,7 @@ def __init__(self, version: Version): self._uri = "/Credentials" - def create( + def _create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -394,19 +707,12 @@ def create( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Create the CredentialInstance + Internal helper for create operation - :param type: - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` - :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` - :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. - :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. - :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. - - :returns: The created CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -422,13 +728,15 @@ def create( ) headers = values.of({"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 CredentialInstance(self._version, payload) - - async def create_async( + def create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -439,7 +747,7 @@ async def create_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronously create the CredentialInstance + Create the CredentialInstance :param type: :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. @@ -451,6 +759,68 @@ async def create_async( :returns: The created CredentialInstance """ + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -465,12 +835,83 @@ async def create_async( ) headers = values.of({"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, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload) + async def create_with_http_info_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -521,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, @@ -540,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -566,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( @@ -574,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, @@ -598,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( @@ -625,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 71825fe578..2d4c6b097d 100644 --- a/twilio/rest/chat/v1/service/__init__.py +++ b/twilio/rest/chat/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -94,6 +95,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -129,6 +131,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -147,6 +167,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -495,121 +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, @@ -665,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. @@ -724,86 +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": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": serialize.boolean_to_string( - notifications_new_message_enabled - ), - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( - notifications_added_to_channel_enabled - ), - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( - notifications_removed_from_channel_enabled - ), - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( - notifications_invited_to_channel_enabled - ), - "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "WebhookMethod": webhook_method, - "WebhookFilters": serialize.map(webhook_filters, lambda e: e), - "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, - "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, - "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, - "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, - "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, - "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, - "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, - "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, - "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, - "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, - "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, - "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, - "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, - "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, - "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, - "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, - "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, - "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, - "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, - "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, - "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, - "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, - "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, - "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, - "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, - "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, - "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, - "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, - "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, - "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, - "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, - "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, - "Limits.ChannelMembers": limits_channel_members, - "Limits.UserChannels": limits_user_channels, - } - ) - - payload = 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, @@ -859,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. @@ -918,8 +822,832 @@ 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 """ + 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, @@ -988,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: @@ -1051,6 +2131,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -1075,13 +2156,12 @@ def __init__(self, version: Version): self._uri = "/Services" - def create(self, friendly_name: str) -> ServiceInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the ServiceInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -1091,19 +2171,43 @@ def create(self, friendly_name: str) -> ServiceInstance: ) headers = values.of({"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, 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( @@ -1113,12 +2217,39 @@ async def create_async(self, friendly_name: str) -> ServiceInstance: ) headers = values.of({"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, 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, @@ -1169,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, @@ -1188,6 +2369,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -1214,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( @@ -1222,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, @@ -1246,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( @@ -1273,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 02c42f65cc..d65a59603b 100644 --- a/twilio/rest/chat/v1/service/channel/__init__.py +++ b/twilio/rest/chat/v1/service/channel/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[ChannelContext] = None @property @@ -120,6 +122,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ChannelInstance": """ Fetch the ChannelInstance @@ -138,6 +158,24 @@ async def fetch_async(self) -> "ChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -180,6 +218,48 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + @property def invites(self) -> InviteList: """ @@ -234,6 +314,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._members: Optional[MemberList] = None self._messages: Optional[MessageList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ChannelInstance @@ -241,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: @@ -253,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: @@ -265,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: """ @@ -285,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 + Internal helper for update operation - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. - :param attributes: A valid JSON string that contains application-specific data. - - :returns: The updated ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -320,13 +496,34 @@ def update( "Attributes": attributes, } ) + 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, + 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, @@ -334,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, @@ -356,13 +577,34 @@ async def update_async( "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, + 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, @@ -370,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: """ @@ -427,6 +695,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: :param payload: Payload response from the API """ + return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -458,22 +727,18 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Channels".format(**self._solution) - def create( + def _create( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, type: Union["ChannelInstance.ChannelType", object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Create the ChannelInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. - :param attributes: A valid JSON string that contains application-specific data. - :param type: - - :returns: The created ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -486,30 +751,81 @@ def create( ) headers = values.of({"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, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: The created ChannelInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, type: Union["ChannelInstance.ChannelType", object] = values.unset, - ) -> ChannelInstance: + ) -> ApiResponse: """ - Asynchronously create the ChannelInstance + Create the ChannelInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. :param attributes: A valid JSON string that contains application-specific data. :param type: - :returns: The created ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -522,14 +838,69 @@ async def create_async( ) headers = values.of({"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, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: The created ChannelInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ChannelInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -584,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, @@ -605,6 +1032,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -634,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( @@ -643,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, @@ -670,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, @@ -700,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: """ @@ -715,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: """ @@ -727,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 c80732a2c0..d88124ec63 100644 --- a/twilio/rest/chat/v1/service/channel/invite.py +++ b/twilio/rest/chat/v1/service/channel/invite.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InviteContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InviteInstance": """ Fetch the InviteInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "InviteInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,6 +194,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InviteInstance @@ -163,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: @@ -175,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: @@ -187,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: """ @@ -208,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: """ @@ -240,6 +378,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: :param payload: Payload response from the API """ + return InviteInstance( self._version, payload, @@ -278,16 +417,14 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> tuple: """ - Create the InviteInstance - - :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. + Internal helper for create operation - :returns: The created InviteInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -298,10 +435,26 @@ def create( ) headers = values.of({"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, 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, @@ -309,16 +462,36 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> ApiResponse: """ - Asynchronously create the InviteInstance + Create the InviteInstance and return response metadata :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. - :returns: The created InviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -329,10 +502,26 @@ async def create_async( ) headers = values.of({"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, 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, @@ -340,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, @@ -394,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, @@ -415,6 +682,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -444,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( @@ -453,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, @@ -480,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, @@ -510,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: """ @@ -525,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: """ @@ -537,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 405662f02d..392847cb06 100644 --- a/twilio/rest/chat/v1/service/channel/member.py +++ b/twilio/rest/chat/v1/service/channel/member.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MemberContext] = None @property @@ -109,6 +111,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MemberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MemberInstance": """ Fetch the MemberInstance @@ -127,6 +147,24 @@ async def fetch_async(self) -> "MemberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, role_sid: Union[str, object] = values.unset, @@ -163,6 +201,42 @@ async def update_async( last_consumed_message_index=last_consumed_message_index, ) + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP info + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance with HTTP info + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -198,6 +272,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MemberInstance @@ -205,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: @@ -217,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: @@ -229,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: """ @@ -250,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, @@ -298,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" - 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, + 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, @@ -332,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 @@ -350,6 +610,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -388,16 +649,14 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> MemberInstance: + ) -> tuple: """ - Create the MemberInstance - - :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. - :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + Internal helper for create operation - :returns: The created MemberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -408,10 +667,26 @@ def create( ) headers = values.of({"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, 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, @@ -419,16 +694,36 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> MemberInstance: + ) -> ApiResponse: """ - Asynchronously create the MemberInstance + Create the MemberInstance and return response metadata :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). - :returns: The created MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -439,10 +734,26 @@ async def create_async( ) headers = values.of({"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, 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, @@ -450,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, @@ -504,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, @@ -525,6 +914,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -554,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( @@ -563,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, @@ -590,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, @@ -620,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: """ @@ -635,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: """ @@ -647,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 34d9e01fb3..11824c42ed 100644 --- a/twilio/rest/chat/v1/service/channel/message.py +++ b/twilio/rest/chat/v1/service/channel/message.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -114,6 +116,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -132,6 +152,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, body: Union[str, object] = values.unset, @@ -168,6 +206,42 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + body=body, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + body=body, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -203,6 +277,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MessageInstance @@ -210,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: @@ -222,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: @@ -234,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: """ @@ -255,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 - - :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. + Internal helper for update operation - :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, @@ -303,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({}) + + 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, + 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, @@ -337,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 @@ -355,6 +609,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, @@ -393,20 +648,17 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, body: str, from_: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance + Internal helper for create operation - :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. - :param from_: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message's author. The default value is `system`. - :param attributes: A valid JSON string that contains application-specific data. - - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -418,10 +670,30 @@ def create( ) headers = values.of({"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, + 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, @@ -429,20 +701,43 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, body: str, from_: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> ApiResponse: """ - Asynchronously create the MessageInstance + Create the MessageInstance and return response metadata :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. :param from_: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message's author. The default value is `system`. :param attributes: A valid JSON string that contains application-specific data. - :returns: The created MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + body=body, from_=from_, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -454,10 +749,32 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -465,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, @@ -519,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, @@ -540,6 +939,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -569,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( @@ -578,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, @@ -605,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, @@ -635,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: """ @@ -650,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: """ @@ -662,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 3ed57a6ee2..a17f74eb7c 100644 --- a/twilio/rest/chat/v1/service/role.py +++ b/twilio/rest/chat/v1/service/role.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[RoleContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoleInstance": """ Fetch the RoleInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "RoleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, permission: List[str]) -> "RoleInstance": """ Update the RoleInstance @@ -145,6 +183,30 @@ async def update_async(self, permission: List[str]) -> "RoleInstance": permission=permission, ) + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + permission=permission, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -174,6 +236,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoleInstance @@ -181,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: @@ -193,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: @@ -205,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: """ @@ -225,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, @@ -238,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({}) + + 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, 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, @@ -265,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, @@ -292,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 @@ -310,6 +528,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -341,17 +560,14 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Roles".format(**self._solution) - def create( + def _create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> tuple: """ - Create the RoleInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param type: - :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. - - :returns: The created RoleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -363,25 +579,61 @@ def create( ) headers = values.of({"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, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The created RoleInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> ApiResponse: """ - Asynchronously create the RoleInstance + Create the RoleInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. :param type: :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. - :returns: The created RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -393,14 +645,53 @@ async def create_async( ) headers = values.of({"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, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The created RoleInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -451,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, @@ -470,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -496,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( @@ -504,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, @@ -528,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, @@ -555,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: """ @@ -570,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: """ @@ -582,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 13c4b9bef6..69a785ce4f 100644 --- a/twilio/rest/chat/v1/service/user/__init__.py +++ b/twilio/rest/chat/v1/service/user/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,6 +76,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -111,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserInstance": """ Fetch the UserInstance @@ -129,6 +149,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, role_sid: Union[str, object] = values.unset, @@ -171,6 +209,48 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + @property def user_channels(self) -> UserChannelList: """ @@ -209,6 +289,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._user_channels: Optional[UserChannelList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserInstance @@ -216,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: @@ -228,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: @@ -240,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: """ @@ -260,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, @@ -295,13 +471,34 @@ 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, + 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, @@ -309,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, @@ -331,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, @@ -345,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: """ @@ -376,6 +644,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserInstance: :param payload: Payload response from the API """ + return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -407,22 +676,18 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Users".format(**self._solution) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Create the UserInstance + Internal helper for create operation - :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. - :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. - :param attributes: A valid JSON string that contains application-specific data. - :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. - - :returns: The created UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -435,30 +700,81 @@ def create( ) headers = values.of({"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, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + payload, _, _ = self._create( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> ApiResponse: """ - Asynchronously create the UserInstance + Create the UserInstance and return response metadata :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. :param attributes: A valid JSON string that contains application-specific data. :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. - :returns: The created UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -471,14 +787,69 @@ async def create_async( ) headers = values.of({"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, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -529,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, @@ -548,6 +969,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -574,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( @@ -582,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, @@ -606,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, @@ -633,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: """ @@ -648,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: """ @@ -660,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 01e639ceab..604cbddec5 100644 --- a/twilio/rest/chat/v1/service/user/user_channel.py +++ b/twilio/rest/chat/v1/service/user/user_channel.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -82,6 +83,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: :param payload: Payload response from the API """ + return UserChannelInstance( self._version, payload, @@ -170,6 +172,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -189,6 +241,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -215,6 +268,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -223,6 +277,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -247,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, @@ -274,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: """ @@ -289,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: """ @@ -301,7 +485,7 @@ async def get_page_async(self, target_url: str) -> UserChannelPage: :returns: Page of UserChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/chat/v2/credential.py b/twilio/rest/chat/v2/credential.py index b098f6820c..40c972a9c2 100644 --- a/twilio/rest/chat/v2/credential.py +++ b/twilio/rest/chat/v2/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -174,6 +212,66 @@ async def update_async( secret=secret, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,6 +299,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -208,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: @@ -220,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: @@ -232,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: """ @@ -251,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, @@ -284,6 +514,64 @@ 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, @@ -294,14 +582,15 @@ def update( "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, @@ -324,24 +613,47 @@ async def update_async( :returns: The updated CredentialInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": serialize.boolean_to_string(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: """ @@ -361,6 +673,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: :param payload: Payload response from the API """ + return CredentialInstance(self._version, payload) def __repr__(self) -> str: @@ -385,7 +698,7 @@ def __init__(self, version: Version): self._uri = "/Credentials" - def create( + def _create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -394,19 +707,12 @@ def create( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Create the CredentialInstance + Internal helper for create operation - :param type: - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` - :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` - :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. - :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. - :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. - - :returns: The created CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -422,13 +728,15 @@ def create( ) headers = values.of({"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 CredentialInstance(self._version, payload) - - async def create_async( + def create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -439,7 +747,7 @@ async def create_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronously create the CredentialInstance + Create the CredentialInstance :param type: :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. @@ -451,6 +759,68 @@ async def create_async( :returns: The created CredentialInstance """ + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -465,12 +835,83 @@ async def create_async( ) headers = values.of({"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, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload) + async def create_with_http_info_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -521,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, @@ -540,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -566,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( @@ -574,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, @@ -598,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( @@ -625,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 376043aed6..de0bab251a 100644 --- a/twilio/rest/chat/v2/service/__init__.py +++ b/twilio/rest/chat/v2/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -103,6 +104,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -138,6 +140,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -156,6 +176,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -370,129 +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, @@ -527,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. @@ -563,67 +479,43 @@ def update( :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. :param notifications_log_enabled: Whether to log notifications. The default is `false`. - :returns: The updated ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": serialize.boolean_to_string( - notifications_new_message_enabled - ), - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.NewMessage.Sound": notifications_new_message_sound, - "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( - notifications_new_message_badge_count_enabled - ), - "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( - notifications_added_to_channel_enabled - ), - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, - "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( - notifications_removed_from_channel_enabled - ), - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, - "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( - notifications_invited_to_channel_enabled - ), - "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, - "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "WebhookMethod": webhook_method, - "WebhookFilters": serialize.map(webhook_filters, lambda e: e), - "Limits.ChannelMembers": limits_channel_members, - "Limits.UserChannels": limits_user_channels, - "Media.CompatibilityMessage": media_compatibility_message, - "PreWebhookRetryCount": pre_webhook_retry_count, - "PostWebhookRetryCount": post_webhook_retry_count, - "Notifications.LogEnabled": serialize.boolean_to_string( - notifications_log_enabled - ), - } - ) - - 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, @@ -658,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. @@ -694,42 +586,656 @@ async def update_async( :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. :param notifications_log_enabled: Whether to log notifications. The default is `false`. - :returns: The updated ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "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, + 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, @@ -745,14 +1251,232 @@ async def update_async( ), } ) + 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 - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + :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`. - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + :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: @@ -820,6 +1544,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -844,13 +1569,12 @@ def __init__(self, version: Version): self._uri = "/Services" - def create(self, friendly_name: str) -> ServiceInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the ServiceInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the new resource. - - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -860,19 +1584,43 @@ def create(self, friendly_name: str) -> ServiceInstance: ) headers = values.of({"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, 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( @@ -882,12 +1630,39 @@ async def create_async(self, friendly_name: str) -> ServiceInstance: ) headers = values.of({"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, 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, @@ -938,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, @@ -957,6 +1782,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -983,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( @@ -991,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, @@ -1015,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( @@ -1042,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 2f960c5135..cd5b0d1dc0 100644 --- a/twilio/rest/chat/v2/service/binding.py +++ b/twilio/rest/chat/v2/service/binding.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[BindingContext] = None @property @@ -112,6 +114,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "BindingInstance": """ Fetch the BindingInstance @@ -130,6 +150,24 @@ async def fetch_async(self) -> "BindingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -159,6 +197,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the BindingInstance @@ -166,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: @@ -178,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: @@ -190,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: """ @@ -210,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: """ @@ -241,6 +377,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: :param payload: Payload response from the API """ + return BindingInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -334,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, @@ -357,6 +554,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -389,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( @@ -399,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, @@ -429,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, @@ -462,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: """ @@ -477,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: """ @@ -489,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 b3796c30d8..d2c4bf396c 100644 --- a/twilio/rest/chat/v2/service/channel/__init__.py +++ b/twilio/rest/chat/v2/service/channel/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -89,6 +90,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[ChannelContext] = None @property @@ -141,6 +143,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "ChannelInstance": """ Fetch the ChannelInstance @@ -159,6 +195,24 @@ async def fetch_async(self) -> "ChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -229,6 +283,76 @@ async def update_async( created_by=created_by, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + @property def invites(self) -> InviteList: """ @@ -291,6 +415,30 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._messages: Optional[MessageList] = None self._webhooks: Optional[WebhookList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -304,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, @@ -325,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: @@ -342,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: """ @@ -362,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 @@ -386,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 - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. - :param attributes: A valid JSON string that contains application-specific data. - :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. - :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. - :param created_by: The `identity` of the User that created the channel. Default is: `system`. + Internal helper for update operation - :returns: The updated ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -410,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 @@ -440,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. @@ -452,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, @@ -479,8 +716,181 @@ async def update_async( sid=self._solution["sid"], ) - @property - def invites(self) -> InviteList: + 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 """ @@ -549,6 +959,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: :param payload: Payload response from the API """ + return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -580,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 @@ -592,20 +1003,12 @@ def create( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, created_by: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Create the ChannelInstance - - :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( @@ -626,15 +1029,56 @@ def create( } ) - 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 @@ -646,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. @@ -659,7 +1103,41 @@ async def create_async( :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used in cases where a Channel is being recreated from a backup/separate source and where a Message was previously updated. :param created_by: The `identity` of the User that created the channel. Default is: `system`. - :returns: The created ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -680,14 +1158,97 @@ async def create_async( } ) - 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, @@ -742,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, @@ -763,6 +1380,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -792,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( @@ -801,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, @@ -828,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, @@ -858,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: """ @@ -873,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: """ @@ -885,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 d0ef32e345..1a3be5b92a 100644 --- a/twilio/rest/chat/v2/service/channel/invite.py +++ b/twilio/rest/chat/v2/service/channel/invite.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InviteContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InviteInstance": """ Fetch the InviteInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "InviteInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,6 +194,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InviteInstance @@ -163,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: @@ -175,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: @@ -187,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: """ @@ -208,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: """ @@ -240,6 +378,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: :param payload: Payload response from the API """ + return InviteInstance( self._version, payload, @@ -278,16 +417,14 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> tuple: """ - Create the InviteInstance - - :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. + Internal helper for create operation - :returns: The created InviteInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -298,10 +435,26 @@ def create( ) headers = values.of({"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, 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, @@ -309,16 +462,36 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> ApiResponse: """ - Asynchronously create the InviteInstance + Create the InviteInstance and return response metadata :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. - :returns: The created InviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -329,10 +502,26 @@ async def create_async( ) headers = values.of({"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, 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, @@ -340,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, @@ -394,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, @@ -415,6 +682,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -444,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( @@ -453,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, @@ -480,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, @@ -510,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: """ @@ -525,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: """ @@ -537,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 95e737b82a..9e40454a44 100644 --- a/twilio/rest/chat/v2/service/channel/member.py +++ b/twilio/rest/chat/v2/service/channel/member.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MemberContext] = None @property @@ -132,6 +134,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "MemberInstance": """ Fetch the MemberInstance @@ -150,6 +186,24 @@ async def fetch_async(self) -> "MemberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -220,6 +274,76 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -255,6 +379,30 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -268,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, @@ -289,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: @@ -306,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: """ @@ -327,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 @@ -352,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, @@ -378,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 @@ -409,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). @@ -421,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, @@ -451,13 +687,191 @@ async def update_async( 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()) + 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 + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) return "".format(context) @@ -469,6 +883,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -507,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[ @@ -519,20 +934,12 @@ def create( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MemberInstance: + ) -> tuple: """ - Create the MemberInstance - - :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. + Internal helper for create operation - :returns: The created MemberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -555,10 +962,51 @@ def create( } ) - 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, @@ -566,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[ @@ -578,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 @@ -591,7 +1039,44 @@ async def create_async( :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used when a Member is being recreated from a backup/separate source and where a Member was previously updated. :param attributes: A valid JSON string that contains application-specific data. - :returns: The created MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -614,10 +1099,51 @@ async def create_async( } ) - 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, @@ -625,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, @@ -679,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, @@ -700,6 +1327,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -729,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( @@ -738,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, @@ -765,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, @@ -795,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: """ @@ -810,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: """ @@ -822,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 1b2892176e..ee6de8ed3d 100644 --- a/twilio/rest/chat/v2/service/channel/message.py +++ b/twilio/rest/chat/v2/service/channel/message.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -87,6 +88,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -140,6 +142,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -158,6 +194,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -228,6 +282,76 @@ async def update_async( from_=from_, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -263,6 +387,30 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -276,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, @@ -297,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: @@ -314,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: """ @@ -335,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 @@ -360,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, @@ -384,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 @@ -415,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. @@ -427,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, @@ -455,15 +693,191 @@ async def update_async( 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) - + 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): @@ -473,6 +887,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, @@ -511,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 @@ -523,20 +938,12 @@ def create( last_updated_by: Union[str, object] = values.unset, body: Union[str, object] = values.unset, media_sid: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance - - :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( @@ -557,10 +964,51 @@ def create( } ) - 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, @@ -568,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 @@ -580,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`. @@ -593,7 +1041,44 @@ async def create_async( :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. - :returns: The created MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -614,10 +1099,51 @@ async def create_async( } ) - 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, @@ -625,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, @@ -679,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, @@ -700,6 +1327,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -729,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( @@ -738,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, @@ -765,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, @@ -795,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: """ @@ -810,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: """ @@ -822,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 bc38198256..f5372f3595 100644 --- a/twilio/rest/chat/v2/service/channel/webhook.py +++ b/twilio/rest/chat/v2/service/channel/webhook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[WebhookContext] = None @property @@ -111,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WebhookInstance": """ Fetch the WebhookInstance @@ -129,6 +149,24 @@ async def fetch_async(self) -> "WebhookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, configuration_url: Union[str, object] = values.unset, @@ -189,6 +227,66 @@ async def update_async( configuration_retry_count=configuration_retry_count, ) + def update_with_http_info( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + + async def update_with_http_info_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -224,6 +322,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WebhookInstance @@ -231,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: @@ -243,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: @@ -255,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: """ @@ -276,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, @@ -298,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 + Internal helper for update operation - :param configuration_url: The URL of the webhook to call using the `configuration.method`. - :param configuration_method: - :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). - :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. - :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. - :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. - - :returns: The updated WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Configuration.Url": configuration_url, @@ -325,13 +518,45 @@ def update( "Configuration.RetryCount": configuration_retry_count, } ) + 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, + 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, @@ -340,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, @@ -348,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: @@ -359,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, @@ -375,49 +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) - - -class WebhookPage(Page): + Asynchronous coroutine to update the WebhookInstance - 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 """ @@ -446,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, @@ -455,19 +784,12 @@ def create( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_retry_count: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Create the WebhookInstance - - :param type: - :param configuration_url: The URL of the webhook to call using the `configuration.method`. - :param configuration_method: - :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). - :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. - :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` is `studio`. - :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + Internal helper for create operation - :returns: The created WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -487,10 +809,46 @@ def create( ) headers = values.of({"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, + 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, @@ -498,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, @@ -507,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`. @@ -519,7 +877,40 @@ async def create_async( :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` is `studio`. :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. - :returns: The created WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -539,10 +930,46 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -550,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, @@ -600,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, @@ -619,6 +1136,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -645,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( @@ -653,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, @@ -677,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, @@ -704,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: """ @@ -719,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: """ @@ -731,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 bcc0b6e5a9..3c6fff8f9c 100644 --- a/twilio/rest/chat/v2/service/role.py +++ b/twilio/rest/chat/v2/service/role.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[RoleContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoleInstance": """ Fetch the RoleInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "RoleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, permission: List[str]) -> "RoleInstance": """ Update the RoleInstance @@ -145,6 +183,30 @@ async def update_async(self, permission: List[str]) -> "RoleInstance": permission=permission, ) + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + permission=permission, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -174,6 +236,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoleInstance @@ -181,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: @@ -193,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: @@ -205,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: """ @@ -225,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, @@ -238,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({}) + + 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, 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, @@ -265,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, @@ -292,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 @@ -310,6 +528,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -341,17 +560,14 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Roles".format(**self._solution) - def create( + def _create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> tuple: """ - Create the RoleInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param type: - :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. - - :returns: The created RoleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -363,25 +579,61 @@ def create( ) headers = values.of({"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, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> ApiResponse: """ - Asynchronously create the RoleInstance + Create the RoleInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. :param type: :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. - :returns: The created RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -393,14 +645,53 @@ async def create_async( ) headers = values.of({"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, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -451,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, @@ -470,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -496,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( @@ -504,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, @@ -528,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, @@ -555,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: """ @@ -570,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: """ @@ -582,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 768b78876e..b31d666b71 100644 --- a/twilio/rest/chat/v2/service/user/__init__.py +++ b/twilio/rest/chat/v2/service/user/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -81,6 +82,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -117,6 +119,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserInstance": """ Fetch the UserInstance @@ -135,6 +155,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -187,6 +225,58 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + @property def user_bindings(self) -> UserBindingList: """ @@ -233,6 +323,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._user_bindings: Optional[UserBindingList] = None self._user_channels: Optional[UserChannelList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserInstance @@ -240,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: @@ -252,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: @@ -264,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: """ @@ -284,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 @@ -305,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, @@ -323,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, @@ -340,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 @@ -348,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, @@ -366,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, @@ -383,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: """ @@ -427,6 +743,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserInstance: :param payload: Payload response from the API """ + return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -458,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[ @@ -467,17 +784,12 @@ def create( role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Create the UserInstance - - :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( @@ -495,15 +807,47 @@ def create( } ) - 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[ @@ -512,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 @@ -522,7 +866,35 @@ async def create_async( :param attributes: A valid JSON string that contains application-specific data. :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. - :returns: The created UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -540,14 +912,79 @@ async def create_async( } ) - 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, @@ -598,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, @@ -617,6 +1104,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -643,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( @@ -651,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, @@ -675,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, @@ -702,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: """ @@ -717,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: """ @@ -729,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 4170c74fb6..9d9ae604ef 100644 --- a/twilio/rest/chat/v2/service/user/user_binding.py +++ b/twilio/rest/chat/v2/service/user/user_binding.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -78,6 +79,7 @@ def __init__( "user_sid": user_sid, "sid": sid or self.sid, } + self._context: Optional[UserBindingContext] = None @property @@ -115,6 +117,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserBindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserBindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserBindingInstance": """ Fetch the UserBindingInstance @@ -133,6 +153,24 @@ async def fetch_async(self) -> "UserBindingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserBindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserBindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -166,6 +204,20 @@ def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserBindingInstance @@ -173,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: @@ -185,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: @@ -197,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: """ @@ -218,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: """ @@ -250,6 +388,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: :param payload: Payload response from the API """ + return UserBindingInstance( self._version, payload, @@ -348,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[ @@ -371,6 +570,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -402,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( @@ -411,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[ @@ -440,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, @@ -472,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: """ @@ -487,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: """ @@ -499,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 1fd25254a5..1c4fe1c849 100644 --- a/twilio/rest/chat/v2/service/user/user_channel.py +++ b/twilio/rest/chat/v2/service/user/user_channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -27,7 +28,7 @@ class UserChannelInstance(InstanceResource): class ChannelStatus(object): JOINED = "joined" INVITED = "invited" - NOT_PARTICIPATING = "not_participating" + NOTPARTICIPATING = "notParticipating" class NotificationLevel(object): DEFAULT = "default" @@ -86,6 +87,7 @@ def __init__( "user_sid": user_sid, "channel_sid": channel_sid or self.channel_sid, } + self._context: Optional[UserChannelContext] = None @property @@ -139,6 +141,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "UserChannelInstance": """ Fetch the UserChannelInstance @@ -157,6 +193,24 @@ async def fetch_async(self) -> "UserChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, notification_level: Union[ @@ -203,6 +257,52 @@ async def update_async( last_consumption_timestamp=last_consumption_timestamp, ) + def update_with_http_info( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserChannelInstance with HTTP info + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + + async def update_with_http_info_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserChannelInstance with HTTP info + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -240,6 +340,30 @@ def __init__( ) ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -253,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, @@ -274,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: @@ -291,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: """ @@ -312,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, @@ -352,13 +580,38 @@ def update( ), } ) + 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[ + "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, @@ -367,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, @@ -393,13 +675,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: 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, @@ -408,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 @@ -426,6 +764,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: :param payload: Payload response from the API """ + return UserChannelInstance( self._version, payload, @@ -514,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, @@ -533,6 +922,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -559,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( @@ -567,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, @@ -591,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, @@ -618,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: """ @@ -633,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: """ @@ -645,7 +1166,7 @@ async def get_page_async(self, target_url: str) -> UserChannelPage: :returns: Page of UserChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) def get(self, channel_sid: str) -> UserChannelContext: """ diff --git a/twilio/rest/chat/v3/channel.py b/twilio/rest/chat/v3/channel.py index e9d10b55bf..fa71c46897 100644 --- a/twilio/rest/chat/v3/channel.py +++ b/twilio/rest/chat/v3/channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def __init__( "service_sid": service_sid or self.service_sid, "sid": sid or self.sid, } + self._context: Optional[ChannelContext] = None @property @@ -148,6 +150,52 @@ async def update_async( messaging_service_sid=messaging_service_sid, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -177,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/messaging/api/service-resource) 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" + + headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: The updated ChannelInstance + """ + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) return ChannelInstance( self._version, payload, @@ -217,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/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, @@ -257,6 +393,36 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + instance = ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/content/v1/content/__init__.py b/twilio/rest/content/v1/content/__init__.py index 0fcbd1c19e..5432e54944 100644 --- a/twilio/rest/content/v1/content/__init__.py +++ b/twilio/rest/content/v1/content/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -26,73 +27,1878 @@ 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" + 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. + :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-api/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], sid: Optional[str] = None + ): + 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") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[ContentContext] = None + + @property + def _proxy(self) -> "ContentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ContentContext for this ContentInstance + """ + if self._context is None: + self._context = ContentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ContentInstance + + + :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") - class CardActionType(object): - URL = "URL" - PHONE_NUMBER = "PHONE_NUMBER" - QUICK_REPLY = "QUICK_REPLY" + 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 QuickReplyActionType(object): - QUICK_REPLY = "QUICK_REPLY" + class TwilioListPicker(object): + """ + :ivar body: + :ivar button: + :ivar items: + """ - """ - :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-api/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, payload: Dict[str, Any]): - def __init__( - self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None - ): - super().__init__(version) + self.body: Optional[str] = payload.get("body") + self.button: Optional[str] = payload.get("button") + self.items: Optional[List[ContentList.ListItem]] = payload.get("items") - 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 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 or self.sid, + "sid": sid, } - self._context: Optional[ContentContext] = None + self._uri = "/Content/{sid}".format(**self._solution) - @property - def _proxy(self) -> "ContentContext": + self._approval_create: Optional[ApprovalCreateList] = None + self._approval_fetch: Optional[ApprovalFetchList] = None + + def _delete(self) -> tuple: """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context + Internal helper for delete operation - :returns: ContentContext for this ContentInstance + Returns: + tuple: (success_boolean, status_code, headers) """ - if self._context is None: - self._context = ContentContext( - self._version, - sid=self._solution["sid"], - ) - return self._context + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) def delete(self) -> bool: """ @@ -101,7 +1907,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._proxy.delete() + 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: """ @@ -110,131 +1941,206 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._proxy.delete_async() + success, _, _ = await self._delete_async() + return success - def fetch(self) -> "ContentInstance": + async def delete_with_http_info_async(self) -> ApiResponse: """ - Fetch the ContentInstance + Asynchronous coroutine that deletes the ContentInstance and return response metadata - :returns: The fetched ContentInstance + :returns: ApiResponse with success boolean, status code, and headers """ - return self._proxy.fetch() + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) - async def fetch_async(self) -> "ContentInstance": + def _fetch(self) -> tuple: """ - Asynchronous coroutine to fetch the ContentInstance + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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 """ - return await self._proxy.fetch_async() + payload, _, _ = self._fetch() + return ContentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - @property - def approval_create(self) -> ApprovalCreateList: + def fetch_with_http_info(self) -> ApiResponse: """ - Access the approval_create + Fetch the ContentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers """ - return self._proxy.approval_create + 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) - @property - def approval_fetch(self) -> ApprovalFetchList: + async def _fetch_async(self) -> tuple: """ - Access the approval_fetch + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - return self._proxy.approval_fetch - def __repr__(self) -> str: + headers = values.of({}) + + headers["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: """ - Provide a friendly representation + Asynchronous coroutine to fetch the ContentInstance - :returns: Machine friendly representation + + :returns: The fetched ContentInstance """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) + 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 -class ContentContext(InstanceContext): - def __init__(self, version: Version, sid: str): + :returns: ApiResponse with instance, status code, and headers """ - Initialize the ContentContext + 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) - :param version: Version that contains the resource - :param sid: The Twilio-provided string that uniquely identifies the Content resource to fetch. + def _update(self, content_update_request: ContentUpdateRequest) -> tuple: """ - super().__init__(version) + Internal helper for update operation - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/Content/{sid}".format(**self._solution) + Returns: + tuple: (payload, status_code, headers) + """ + data = content_update_request.to_dict() - self._approval_create: Optional[ApprovalCreateList] = None - self._approval_fetch: Optional[ApprovalFetchList] = None + headers = values.of({}) - def delete(self) -> bool: + 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: """ - Deletes the ContentInstance + Update the ContentInstance + :param content_update_request: - :returns: True if delete succeeds, False otherwise + :returns: The updated ContentInstance """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) + payload, _, _ = self._update(content_update_request=content_update_request) + return ContentInstance(self._version, payload, sid=self._solution["sid"]) - async def delete_async(self) -> bool: + def update_with_http_info( + self, content_update_request: ContentUpdateRequest + ) -> ApiResponse: """ - Asynchronous coroutine that deletes the ContentInstance + Update the ContentInstance and return response metadata + :param content_update_request: - :returns: True if delete succeeds, False otherwise + :returns: ApiResponse with instance, status code, and headers """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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) - def fetch(self) -> ContentInstance: + async def _update_async( + self, content_update_request: ContentUpdateRequest + ) -> tuple: """ - Fetch the ContentInstance + Internal async helper for update operation - - :returns: The fetched ContentInstance + Returns: + tuple: (payload, status_code, headers) """ + data = content_update_request.to_dict() - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) + headers = values.of({}) - return ContentInstance( - self._version, - payload, - sid=self._solution["sid"], + 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 fetch_async(self) -> ContentInstance: + async def update_async( + self, content_update_request: ContentUpdateRequest + ) -> ContentInstance: """ - Asynchronous coroutine to fetch the ContentInstance + Asynchronous coroutine to update the ContentInstance + :param content_update_request: - :returns: The fetched ContentInstance + :returns: The updated ContentInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._update_async( + content_update_request=content_update_request ) + return ContentInstance(self._version, payload, sid=self._solution["sid"]) - 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: @@ -278,6 +2184,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ContentInstance: :param payload: Payload response from the API """ + return ContentInstance(self._version, payload) def __repr__(self) -> str: @@ -297,7 +2204,7 @@ class AuthenticationAction(object): :ivar copy_code_text: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.type: Optional["ContentInstance.AuthenticationActionType"] = ( payload.get("type") @@ -316,10 +2223,11 @@ class CallToActionAction(object): :ivar title: :ivar url: :ivar phone: + :ivar code: :ivar id: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.type: Optional["ContentInstance.CallToActionActionType"] = payload.get( "type" @@ -327,6 +2235,7 @@ def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): 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): @@ -335,6 +2244,7 @@ def to_dict(self): "title": self.title, "url": self.url, "phone": self.phone, + "code": self.code, "id": self.id, } @@ -345,15 +2255,51 @@ class CardAction(object): :ivar url: :ivar phone: :ivar id: + :ivar code: + :ivar webview_size: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + 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 { @@ -364,6 +2310,35 @@ def to_dict(self): "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: @@ -374,7 +2349,7 @@ class CatalogItem(object): :ivar description: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.id: Optional[str] = payload.get("id") self.section_title: Optional[str] = payload.get("section_title") @@ -401,19 +2376,91 @@ class ContentCreateRequest(object): :ivar types: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + 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.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") + self.label: Optional[str] = payload.get("label") + self.type: Optional[str] = payload.get("type") def to_dict(self): return { - "friendly_name": self.friendly_name, - "variables": self.variables, - "language": self.language, - "types": self.types.to_dict(), + "label": self.label, + "type": self.type, } class ListItem(object): @@ -423,7 +2470,7 @@ class ListItem(object): :ivar description: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.id: Optional[str] = payload.get("id") self.item: Optional[str] = payload.get("item") @@ -443,7 +2490,7 @@ class QuickReplyAction(object): :ivar id: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.type: Optional["ContentInstance.QuickReplyActionType"] = payload.get( "type" @@ -464,7 +2511,7 @@ class TwilioCallToAction(object): :ivar actions: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.body: Optional[str] = payload.get("body") self.actions: Optional[List[ContentList.CallToActionAction]] = payload.get( @@ -474,7 +2521,11 @@ def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): def to_dict(self): return { "body": self.body, - "actions": [actions.to_dict() for actions in self.actions], + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), } class TwilioCard(object): @@ -485,7 +2536,7 @@ class TwilioCard(object): :ivar actions: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.title: Optional[str] = payload.get("title") self.subtitle: Optional[str] = payload.get("subtitle") @@ -499,7 +2550,32 @@ def to_dict(self): "title": self.title, "subtitle": self.subtitle, "media": self.media, - "actions": [actions.to_dict() for actions in self.actions], + "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): @@ -512,7 +2588,7 @@ class TwilioCatalog(object): :ivar dynamic_items: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.title: Optional[str] = payload.get("title") self.body: Optional[str] = payload.get("body") @@ -527,10 +2603,47 @@ def to_dict(self): "body": self.body, "subtitle": self.subtitle, "id": self.id, - "items": [items.to_dict() for items in self.items], + "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: @@ -538,7 +2651,7 @@ class TwilioListPicker(object): :ivar items: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.body: Optional[str] = payload.get("body") self.button: Optional[str] = payload.get("button") @@ -548,7 +2661,11 @@ def to_dict(self): return { "body": self.body, "button": self.button, - "items": [items.to_dict() for items in self.items], + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), } class TwilioLocation(object): @@ -556,19 +2673,25 @@ class TwilioLocation(object): :ivar latitude: :ivar longitude: :ivar label: + :ivar id: + :ivar address: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + 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): @@ -577,7 +2700,7 @@ class TwilioMedia(object): :ivar media: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.body: Optional[str] = payload.get("body") self.media: Optional[List[str]] = payload.get("media") @@ -594,7 +2717,7 @@ class TwilioQuickReply(object): :ivar actions: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.body: Optional[str] = payload.get("body") self.actions: Optional[List[ContentList.QuickReplyAction]] = payload.get( @@ -604,7 +2727,31 @@ def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): def to_dict(self): return { "body": self.body, - "actions": [actions.to_dict() for actions in self.actions], + "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): @@ -612,7 +2759,7 @@ class TwilioText(object): :ivar body: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.body: Optional[str] = payload.get("body") @@ -631,55 +2778,127 @@ class Types(object): :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], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.twilio_text: Optional[ContentList.TwilioText] = payload.get( - "twilio_text" + "twilio/text" ) self.twilio_media: Optional[ContentList.TwilioMedia] = payload.get( - "twilio_media" + "twilio/media" ) self.twilio_location: Optional[ContentList.TwilioLocation] = payload.get( - "twilio_location" + "twilio/location" ) self.twilio_list_picker: Optional[ContentList.TwilioListPicker] = ( - payload.get("twilio_list_picker") + payload.get("twilio/list-picker") ) self.twilio_call_to_action: Optional[ContentList.TwilioCallToAction] = ( - payload.get("twilio_call_to_action") + payload.get("twilio/call-to-action") ) self.twilio_quick_reply: Optional[ContentList.TwilioQuickReply] = ( - payload.get("twilio_quick_reply") + payload.get("twilio/quick-reply") ) self.twilio_card: Optional[ContentList.TwilioCard] = payload.get( - "twilio_card" + "twilio/card" ) self.twilio_catalog: Optional[ContentList.TwilioCatalog] = payload.get( - "twilio_catalog" + "twilio/catalog" + ) + self.twilio_carousel: Optional[ContentList.TwilioCarousel] = payload.get( + "twilio/carousel" + ) + 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" + "whatsapp/card" ) self.whatsapp_authentication: Optional[ ContentList.WhatsappAuthentication - ] = payload.get("whatsapp_authentication") + ] = payload.get("whatsapp/authentication") + self.whatsapp_flows: Optional[ContentList.WhatsappFlows] = payload.get( + "whatsapp/flows" + ) def to_dict(self): return { - "twilio_text": self.twilio_text.to_dict(), - "twilio_media": self.twilio_media.to_dict(), - "twilio_location": self.twilio_location.to_dict(), - "twilio_list_picker": self.twilio_list_picker.to_dict(), - "twilio_call_to_action": self.twilio_call_to_action.to_dict(), - "twilio_quick_reply": self.twilio_quick_reply.to_dict(), - "twilio_card": self.twilio_card.to_dict(), - "twilio_catalog": self.twilio_catalog.to_dict(), - "whatsapp_card": self.whatsapp_card.to_dict(), - "whatsapp_authentication": self.whatsapp_authentication.to_dict(), + "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): @@ -689,7 +2908,7 @@ class WhatsappAuthentication(object): :ivar actions: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.add_security_recommendation: Optional[bool] = payload.get( "add_security_recommendation" @@ -705,7 +2924,11 @@ 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], + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), } class WhatsappCard(object): @@ -717,7 +2940,7 @@ class WhatsappCard(object): :ivar actions: """ - def __init__(self, payload: Dict[str, Any], sid: Optional[str] = None): + def __init__(self, payload: Dict[str, Any]): self.body: Optional[str] = payload.get("body") self.footer: Optional[str] = payload.get("footer") @@ -733,7 +2956,48 @@ def to_dict(self): "footer": self.footer, "media": self.media, "header_text": self.header_text, - "actions": [actions.to_dict() for actions in self.actions], + "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): @@ -747,6 +3011,25 @@ def __init__(self, version: Version): self._uri = "/Content" + def _create(self, content_create_request: ContentCreateRequest) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = content_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, content_create_request: ContentCreateRequest) -> ContentInstance: """ Create the ContentInstance @@ -755,17 +3038,46 @@ def create(self, content_create_request: ContentCreateRequest) -> ContentInstanc :returns: The created ContentInstance """ + payload, _, _ = self._create(content_create_request=content_create_request) + return ContentInstance(self._version, payload) + + def create_with_http_info( + self, content_create_request: ContentCreateRequest + ) -> ApiResponse: + """ + Create the ContentInstance and return response metadata + + :param content_create_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + content_create_request=content_create_request + ) + instance = ContentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, content_create_request: ContentCreateRequest + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = content_create_request.to_dict() headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Content-Type"] = "application/json" - payload = self._version.create( + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return ContentInstance(self._version, payload) - async def create_async( self, content_create_request: ContentCreateRequest ) -> ContentInstance: @@ -776,16 +3088,26 @@ async def create_async( :returns: The created ContentInstance """ - data = content_create_request.to_dict() + payload, _, _ = await self._create_async( + content_create_request=content_create_request + ) + return ContentInstance(self._version, payload) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - headers["Content-Type"] = "application/json" + async def create_with_http_info_async( + self, content_create_request: ContentCreateRequest + ) -> ApiResponse: + """ + Asynchronously create the ContentInstance and return response metadata - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + :param content_create_request: - return ContentInstance(self._version, payload) + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + content_create_request=content_create_request + ) + instance = ContentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -837,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, @@ -856,6 +3228,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -882,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( @@ -890,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, @@ -914,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( @@ -941,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. @@ -974,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) @@ -982,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 index 6e28052e0d..2487ec6090 100644 --- a/twilio/rest/content/v1/content/approval_create.py +++ b/twilio/rest/content/v1/content/approval_create.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -21,13 +22,31 @@ 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: + :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): @@ -64,7 +83,7 @@ class ContentApprovalRequest(object): :ivar category: A WhatsApp recognized template category. """ - def __init__(self, payload: Dict[str, Any], content_sid: str): + def __init__(self, payload: Dict[str, Any]): self.name: Optional[str] = payload.get("name") self.category: Optional[str] = payload.get("category") @@ -93,6 +112,25 @@ def __init__(self, version: Version, content_sid: str): **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: @@ -103,17 +141,48 @@ def create( :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" - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) + headers["Accept"] = "application/json" - return ApprovalCreateInstance( - self._version, payload, content_sid=self._solution["content_sid"] + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers ) async def create_async( @@ -126,18 +195,30 @@ async def create_async( :returns: The created ApprovalCreateInstance """ - data = content_approval_request.to_dict() + payload, _, _ = await self._create_async( + content_approval_request=content_approval_request + ) + return ApprovalCreateInstance( + self._version, payload, content_sid=self._solution["content_sid"] + ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - headers["Content-Type"] = "application/json" + async def create_with_http_info_async( + self, content_approval_request: ContentApprovalRequest + ) -> ApiResponse: + """ + Asynchronously create the ApprovalCreateInstance and return response metadata - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + :param content_approval_request: - return ApprovalCreateInstance( + :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: """ diff --git a/twilio/rest/content/v1/content/approval_fetch.py b/twilio/rest/content/v1/content/approval_fetch.py index f679a920a1..47b00a89ec 100644 --- a/twilio/rest/content/v1/content/approval_fetch.py +++ b/twilio/rest/content/v1/content/approval_fetch.py @@ -13,6 +13,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 @@ -27,7 +29,7 @@ class ApprovalFetchInstance(InstanceResource): :ivar url: The URL of the resource, relative to `https://content.twilio.com`. """ - def __init__(self, version: Version, payload: Dict[str, Any], content_sid: str): + def __init__(self, version: Version, payload: Dict[str, Any], sid: str): super().__init__(version) self.sid: Optional[str] = payload.get("sid") @@ -36,8 +38,9 @@ def __init__(self, version: Version, payload: Dict[str, Any], content_sid: str): self.url: Optional[str] = payload.get("url") self._solution = { - "content_sid": content_sid, + "sid": sid, } + self._context: Optional[ApprovalFetchContext] = None @property @@ -51,7 +54,7 @@ def _proxy(self) -> "ApprovalFetchContext": if self._context is None: self._context = ApprovalFetchContext( self._version, - content_sid=self._solution["content_sid"], + sid=self._solution["sid"], ) return self._context @@ -73,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 @@ -85,20 +106,36 @@ def __repr__(self) -> str: class ApprovalFetchContext(InstanceContext): - def __init__(self, version: Version, content_sid: str): + def __init__(self, version: Version, sid: str): """ Initialize the ApprovalFetchContext :param version: Version that contains the resource - :param content_sid: The Twilio-provided string that uniquely identifies the Content resource whose approval information to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Content resource whose approval information to fetch. """ super().__init__(version) # Path Solution self._solution = { - "content_sid": content_sid, + "sid": sid, } - self._uri = "/Content/{content_sid}/ApprovalRequests".format(**self._solution) + 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: """ @@ -107,16 +144,42 @@ 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, - content_sid=self._solution["content_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["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: @@ -126,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, - content_sid=self._solution["content_sid"], + sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ @@ -150,19 +223,19 @@ def __repr__(self) -> str: class ApprovalFetchList(ListResource): - def __init__(self, version: Version, content_sid: str): + def __init__(self, version: Version, sid: str): """ Initialize the ApprovalFetchList :param version: Version that contains the resource - :param content_sid: The Twilio-provided string that uniquely identifies the Content resource whose approval information to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Content resource whose approval information to fetch. """ super().__init__(version) # Path Solution self._solution = { - "content_sid": content_sid, + "sid": sid, } def get(self) -> ApprovalFetchContext: @@ -170,18 +243,14 @@ def get(self) -> ApprovalFetchContext: Constructs a ApprovalFetchContext """ - return ApprovalFetchContext( - self._version, content_sid=self._solution["content_sid"] - ) + return ApprovalFetchContext(self._version, sid=self._solution["sid"]) def __call__(self) -> ApprovalFetchContext: """ Constructs a ApprovalFetchContext """ - return ApprovalFetchContext( - self._version, content_sid=self._solution["content_sid"] - ) + return ApprovalFetchContext(self._version, sid=self._solution["sid"]) def __repr__(self) -> str: """ diff --git a/twilio/rest/content/v1/content_and_approvals.py b/twilio/rest/content/v1/content_and_approvals.py index de40cfc172..73c009e1be 100644 --- a/twilio/rest/content/v1/content_and_approvals.py +++ b/twilio/rest/content/v1/content_and_approvals.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ContentAndApprovalsInstance: :param payload: Payload response from the API """ + return ContentAndApprovalsInstance(self._version, payload) def __repr__(self) -> str: @@ -146,6 +148,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ContentAndApprovalsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ContentAndApprovalsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -165,6 +217,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -191,6 +244,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -199,6 +253,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ContentAndApprovalsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ContentAndApprovalsInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -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 cfb4ac698d..a600809360 100644 --- a/twilio/rest/content/v1/legacy_content.py +++ b/twilio/rest/content/v1/legacy_content.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def get_instance(self, payload: Dict[str, Any]) -> LegacyContentInstance: :param payload: Payload response from the API """ + return LegacyContentInstance(self._version, payload) def __repr__(self) -> str: @@ -148,6 +150,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams LegacyContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams LegacyContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -167,6 +219,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -193,6 +246,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -201,6 +255,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists LegacyContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists LegacyContentInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -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/content.py b/twilio/rest/content/v2/content.py index c8abf4dcda..2584c2fd5d 100644 --- a/twilio/rest/content/v2/content.py +++ b/twilio/rest/content/v2/content.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ContentInstance: :param payload: Payload response from the API """ + return ContentInstance(self._version, payload) def __repr__(self) -> str: @@ -204,6 +206,112 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ContentInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ContentInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, sort_by_date: Union[str, object] = values.unset, @@ -241,6 +349,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sort_by_date=sort_by_date, @@ -294,6 +403,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -311,6 +421,110 @@ async def list_async( ) ] + def list_with_http_info( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ContentInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ContentInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, sort_by_date: Union[str, object] = values.unset, @@ -362,7 +576,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( @@ -416,11 +636,139 @@ async def page_async( } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentPage, status code, and headers + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentPage, status code, and headers + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ContentPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ContentPage: """ Retrieve a specific page of ContentInstance records from the API. diff --git a/twilio/rest/content/v2/content_and_approvals.py b/twilio/rest/content/v2/content_and_approvals.py index 4c081b9e22..e383867e93 100644 --- a/twilio/rest/content/v2/content_and_approvals.py +++ b/twilio/rest/content/v2/content_and_approvals.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ContentAndApprovalsInstance: :param payload: Payload response from the API """ + return ContentAndApprovalsInstance(self._version, payload) def __repr__(self) -> str: @@ -204,6 +206,112 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ContentAndApprovalsInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ContentAndApprovalsInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, sort_by_date: Union[str, object] = values.unset, @@ -241,6 +349,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sort_by_date=sort_by_date, @@ -294,6 +403,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -311,6 +421,110 @@ async def list_async( ) ] + def list_with_http_info( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ContentAndApprovalsInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ContentAndApprovalsInstance and returns headers from first page + + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, sort_by_date: Union[str, object] = values.unset, @@ -362,7 +576,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( @@ -416,11 +636,139 @@ async def page_async( } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentAndApprovalsPage, status code, and headers + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ContentAndApprovalsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ContentAndApprovalsPage, status code, and headers + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ContentAndApprovalsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> ContentAndApprovalsPage: """ Retrieve a specific page of ContentAndApprovalsInstance records from the API. diff --git a/twilio/rest/conversations/ConversationsBase.py b/twilio/rest/conversations/ConversationsBase.py index 8904308365..0a34545412 100644 --- a/twilio/rest/conversations/ConversationsBase.py +++ b/twilio/rest/conversations/ConversationsBase.py @@ -14,6 +14,7 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.conversations.v1 import V1 +from twilio.rest.conversations.v2 import V2 class ConversationsBase(Domain): @@ -26,6 +27,7 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://conversations.twilio.com") self._v1: Optional[V1] = None + self._v2: Optional[V2] = None @property def v1(self) -> V1: @@ -36,6 +38,15 @@ def v1(self) -> V1: self._v1 = V1(self) return self._v1 + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Conversations + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/conversations/v1/__init__.py b/twilio/rest/conversations/v1/__init__.py index 3296ba2b46..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, @@ -39,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 @@ -63,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 58bd74be49..3c0864ec2f 100644 --- a/twilio/rest/conversations/v1/address_configuration.py +++ b/twilio/rest/conversations/v1/address_configuration.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -30,8 +31,8 @@ class AutoCreationType(object): DEFAULT = "default" class Method(object): - GET = "GET" - POST = "POST" + GET = "get" + POST = "post" class Type(object): SMS = "sms" @@ -39,6 +40,9 @@ class Type(object): MESSENGER = "messenger" GBM = "gbm" EMAIL = "email" + RCS = "rcs" + APPLE = "apple" + CHAT = "chat" """ :ivar sid: A 34 character string that uniquely identifies this resource. @@ -76,6 +80,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AddressConfigurationContext] = None @property @@ -111,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 @@ -129,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, @@ -215,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 @@ -244,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 @@ -251,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: @@ -263,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: @@ -275,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: """ @@ -294,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, @@ -321,22 +544,14 @@ 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, @@ -354,18 +569,63 @@ def update( "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, } ) + 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, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Update the AddressConfigurationInstance + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: The updated AddressConfigurationInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) return AddressConfigurationInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, auto_creation_enabled: Union[bool, object] = values.unset, @@ -380,9 +640,9 @@ async def update_async( auto_creation_webhook_filters: Union[List[str], object] = values.unset, auto_creation_studio_flow_sid: Union[str, object] = values.unset, auto_creation_studio_retry_count: Union[int, object] = values.unset, - ) -> AddressConfigurationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the AddressConfigurationInstance + Update the AddressConfigurationInstance and return response metadata :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address @@ -394,8 +654,47 @@ async def update_async( :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request - :returns: The updated AddressConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) + instance = AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -413,19 +712,111 @@ async def update_async( "AutoCreation.StudioRetryCount": auto_creation_studio_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 AddressConfigurationInstance( - 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 ) - def __repr__(self) -> str: - """ + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Asynchronous coroutine to update the AddressConfigurationInstance + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: The updated AddressConfigurationInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) + return AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AddressConfigurationInstance and return response metadata + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) + instance = AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ Provide a friendly representation :returns: Machine friendly representation @@ -444,6 +835,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AddressConfigurationInstance: :param payload: Payload response from the API """ + return AddressConfigurationInstance(self._version, payload) def __repr__(self) -> str: @@ -468,7 +860,7 @@ def __init__(self, version: Version): self._uri = "/Configuration/Addresses" - def create( + def _create( self, type: "AddressConfigurationInstance.Type", address: str, @@ -486,24 +878,12 @@ def create( auto_creation_studio_flow_sid: Union[str, object] = values.unset, auto_creation_studio_retry_count: Union[int, object] = values.unset, address_country: Union[str, object] = values.unset, - ) -> AddressConfigurationInstance: + ) -> tuple: """ - Create the AddressConfigurationInstance - - :param type: - :param address: The unique address to be configured. The address can be a whatsapp address or phone number - :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. - :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address - :param auto_creation_type: - :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. - :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. - :param auto_creation_webhook_method: - :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` - :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. - :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request - :param address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + Internal helper for create operation - :returns: The created AddressConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -528,13 +908,15 @@ def create( ) headers = values.of({"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 AddressConfigurationInstance(self._version, payload) - - async def create_async( + def create( self, type: "AddressConfigurationInstance.Type", address: str, @@ -554,7 +936,7 @@ async def create_async( address_country: Union[str, object] = values.unset, ) -> AddressConfigurationInstance: """ - Asynchronously create the AddressConfigurationInstance + Create the AddressConfigurationInstance :param type: :param address: The unique address to be configured. The address can be a whatsapp address or phone number @@ -571,6 +953,101 @@ async def create_async( :returns: The created AddressConfigurationInstance """ + payload, _, _ = self._create( + type=type, + address=address, + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + address_country=address_country, + ) + return AddressConfigurationInstance(self._version, payload) + + def create_with_http_info( + self, + type: "AddressConfigurationInstance.Type", + address: str, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + address_country: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the AddressConfigurationInstance and return response metadata + + :param type: + :param address: The unique address to be configured. The address can be a whatsapp address or phone number + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + :param address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + address=address, + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + address_country=address_country, + ) + instance = AddressConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "AddressConfigurationInstance.Type", + address: str, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + address_country: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -594,12 +1071,121 @@ async def create_async( ) headers = values.of({"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, + type: "AddressConfigurationInstance.Type", + address: str, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + address_country: Union[str, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Asynchronously create the AddressConfigurationInstance + + :param type: + :param address: The unique address to be configured. The address can be a whatsapp address or phone number + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + :param address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + + :returns: The created AddressConfigurationInstance + """ + payload, _, _ = await self._create_async( + type=type, + address=address, + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + address_country=address_country, + ) return AddressConfigurationInstance(self._version, payload) + async def create_with_http_info_async( + self, + type: "AddressConfigurationInstance.Type", + address: str, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + address_country: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the AddressConfigurationInstance and return response metadata + + :param type: + :param address: The unique address to be configured. The address can be a whatsapp address or phone number + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + :param address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + address=address, + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + address_country=address_country, + ) + instance = AddressConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, type: Union[str, object] = values.unset, @@ -654,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, @@ -675,6 +1317,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -704,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( @@ -713,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, @@ -740,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( @@ -770,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 46f511aa1e..ec2a73badd 100644 --- a/twilio/rest/conversations/v1/configuration/__init__.py +++ b/twilio/rest/conversations/v1/configuration/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,24 @@ async def fetch_async(self) -> "ConfigurationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, default_chat_service_sid: Union[str, object] = values.unset, @@ -132,6 +151,54 @@ async def update_async( default_closed_timer=default_closed_timer, ) + def update_with_http_info( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConfigurationInstance with HTTP info + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + default_chat_service_sid=default_chat_service_sid, + default_messaging_service_sid=default_messaging_service_sid, + default_inactive_timer=default_inactive_timer, + default_closed_timer=default_closed_timer, + ) + + async def update_with_http_info_async( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance with HTTP info + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + default_chat_service_sid=default_chat_service_sid, + default_messaging_service_sid=default_messaging_service_sid, + default_inactive_timer=default_inactive_timer, + default_closed_timer=default_closed_timer, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -154,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 @@ -161,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: """ @@ -179,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, @@ -207,6 +356,54 @@ def update( :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, @@ -215,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, @@ -241,22 +439,39 @@ async def update_async( :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: """ diff --git a/twilio/rest/conversations/v1/configuration/webhook.py b/twilio/rest/conversations/v1/configuration/webhook.py index 4ece54232c..d286bba936 100644 --- a/twilio/rest/conversations/v1/configuration/webhook.py +++ b/twilio/rest/conversations/v1/configuration/webhook.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -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 @@ -161,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 @@ -168,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: """ @@ -186,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, @@ -209,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, @@ -225,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, @@ -246,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: """ diff --git a/twilio/rest/conversations/v1/conversation/__init__.py b/twilio/rest/conversations/v1/conversation/__init__.py index 4eb14b769c..808ab297e8 100644 --- a/twilio/rest/conversations/v1/conversation/__init__.py +++ b/twilio/rest/conversations/v1/conversation/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -28,6 +29,7 @@ class ConversationInstance(InstanceResource): class State(object): + INITIALIZING = "initializing" INACTIVE = "inactive" ACTIVE = "active" CLOSED = "closed" @@ -80,6 +82,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ConversationContext] = None @property @@ -131,6 +134,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "ConversationInstance": """ Fetch the ConversationInstance @@ -149,6 +186,24 @@ async def fetch_async(self) -> "ConversationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -249,6 +304,106 @@ async def update_async( bindings_email_name=bindings_email_name, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + @property def messages(self) -> MessageList: """ @@ -301,6 +456,30 @@ def __init__(self, version: Version, sid: str): self._participants: Optional[ParticipantList] = None self._webhooks: Optional[WebhookList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -314,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, @@ -335,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: @@ -352,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: """ @@ -371,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 @@ -399,25 +680,14 @@ def update( unique_name: Union[str, object] = values.unset, bindings_email_address: Union[str, object] = values.unset, bindings_email_name: Union[str, object] = values.unset, - ) -> ConversationInstance: + ) -> tuple: """ - Update the ConversationInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. - :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. - :param state: - :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. - :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. - :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. - :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + Internal helper for update operation - :returns: The updated ConversationInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -433,19 +703,26 @@ def update( "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 @@ -463,7 +740,7 @@ async def update_async( bindings_email_name: Union[str, object] = values.unset, ) -> ConversationInstance: """ - Asynchronous coroutine to update the ConversationInstance + Update the ConversationInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. @@ -480,33 +757,239 @@ async def update_async( :returns: The updated ConversationInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "Attributes": attributes, - "MessagingServiceSid": messaging_service_sid, - "State": state, - "Timers.Inactive": timers_inactive, + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + return ConversationInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConversationInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + instance = ConversationInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "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( - { - "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[ + "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: """ @@ -561,6 +1044,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: :param payload: Payload response from the API """ + return ConversationInstance(self._version, payload) def __repr__(self) -> str: @@ -585,6 +1069,60 @@ def __init__(self, version: Version): self._uri = "/Conversations" + def _create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, x_twilio_webhook_enabled: Union[ @@ -620,6 +1158,97 @@ def create( :returns: The created ConversationInstance """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + return ConversationInstance(self._version, payload) + + def create_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ConversationInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + instance = ConversationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -643,13 +1272,66 @@ def create( } ) - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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_async( + async def create_with_http_info_async( self, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -665,9 +1347,9 @@ async def create_async( timers_closed: Union[str, object] = values.unset, bindings_email_address: Union[str, object] = values.unset, bindings_email_name: Union[str, object] = values.unset, - ) -> ConversationInstance: + ) -> ApiResponse: """ - Asynchronously create the ConversationInstance + Asynchronously create the ConversationInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. @@ -682,36 +1364,24 @@ async def create_async( :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. - :returns: The created ConversationInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "MessagingServiceSid": messaging_service_sid, - "Attributes": attributes, - "State": state, - "Timers.Inactive": timers_inactive, - "Timers.Closed": timers_closed, - "Bindings.Email.Address": bindings_email_address, - "Bindings.Email.Name": bindings_email_name, - } - ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - "Content-Type": "application/x-www-form-urlencoded", - } - ) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + date_created=date_created, + date_updated=date_updated, + messaging_service_sid=messaging_service_sid, + attributes=attributes, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, ) - - return ConversationInstance(self._version, payload) + instance = ConversationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -785,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, @@ -810,6 +1550,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( start_date=start_date, @@ -845,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( @@ -856,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, @@ -889,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( @@ -925,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 8488bee004..4d1345715e 100644 --- a/twilio/rest/conversations/v1/conversation/message/__init__.py +++ b/twilio/rest/conversations/v1/conversation/message/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -86,6 +87,7 @@ def __init__( "conversation_sid": conversation_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -138,6 +140,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -156,6 +192,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -226,6 +280,76 @@ async def update_async( subject=subject, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :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 def delivery_receipts(self) -> DeliveryReceiptList: """ @@ -266,6 +390,30 @@ def __init__(self, version: Version, conversation_sid: str, sid: str): self._delivery_receipts: Optional[DeliveryReceiptList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -279,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, @@ -300,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: @@ -317,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: """ @@ -337,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 @@ -361,20 +613,14 @@ def update( date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, subject: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Update the MessageInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param author: The channel specific identifier of the message's author. Defaults to `system`. - :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. - :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param subject: The subject of the message, can be up to 256 characters long. + Internal helper for update operation - :returns: The updated MessageInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Author": author, @@ -385,24 +631,26 @@ def update( "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 @@ -415,7 +663,7 @@ async def update_async( subject: Union[str, object] = values.unset, ) -> MessageInstance: """ - Asynchronous coroutine to update the MessageInstance + Update the MessageInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param author: The channel specific identifier of the message's author. Defaults to `system`. @@ -427,26 +675,15 @@ async def update_async( :returns: The updated MessageInstance """ - data = values.of( - { - "Author": author, - "Body": body, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "Attributes": attributes, - "Subject": subject, - } - ) - headers = values.of( - { - "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,8 +691,181 @@ async def update_async( sid=self._solution["sid"], ) - @property - def delivery_receipts(self) -> DeliveryReceiptList: + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :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 """ @@ -485,6 +895,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, conversation_sid=self._solution["conversation_sid"] ) @@ -518,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 @@ -532,22 +943,12 @@ def create( content_sid: Union[str, object] = values.unset, content_variables: Union[str, object] = values.unset, subject: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance + Internal helper for create operation - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param author: The channel specific identifier of the message's author. Defaults to `system`. - :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. - :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param media_sid: The Media SID to be attached to the new Message. - :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. - :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. - :param subject: The subject of the message, can be up to 256 characters long. - - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -570,15 +971,62 @@ def create( } ) - 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 @@ -592,9 +1040,9 @@ async def create_async( content_sid: Union[str, object] = values.unset, content_variables: Union[str, object] = values.unset, subject: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> ApiResponse: """ - Asynchronously create the MessageInstance + Create the MessageInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param author: The channel specific identifier of the message's author. Defaults to `system`. @@ -607,7 +1055,45 @@ async def create_async( :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( @@ -630,14 +1116,109 @@ async def create_async( } ) - 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, @@ -692,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, @@ -713,6 +1350,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -742,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( @@ -751,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, @@ -778,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, @@ -808,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: """ @@ -823,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: """ @@ -835,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 16af7892e9..ffebce0840 100644 --- a/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py +++ b/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -78,6 +79,7 @@ def __init__( "message_sid": message_sid, "sid": sid or self.sid, } + self._context: Optional[DeliveryReceiptContext] = None @property @@ -115,6 +117,24 @@ async def fetch_async(self) -> "DeliveryReceiptInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeliveryReceiptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -150,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 @@ -157,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: """ @@ -178,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: """ @@ -210,6 +286,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DeliveryReceiptInstance: :param payload: Payload response from the API """ + return DeliveryReceiptInstance( self._version, payload, @@ -300,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, @@ -319,6 +446,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -345,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( @@ -353,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, @@ -377,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, @@ -404,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: """ @@ -419,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: """ @@ -431,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 92f8e5de40..0600512c97 100644 --- a/twilio/rest/conversations/v1/conversation/participant.py +++ b/twilio/rest/conversations/v1/conversation/participant.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def __init__( "conversation_sid": conversation_sid, "sid": sid or self.sid, } + self._context: Optional[ParticipantContext] = None @property @@ -129,6 +131,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "ParticipantInstance": """ Fetch the ParticipantInstance @@ -147,6 +183,24 @@ async def fetch_async(self) -> "ParticipantInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -235,6 +289,94 @@ async def update_async( last_read_timestamp=last_read_timestamp, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -266,6 +408,30 @@ def __init__(self, version: Version, conversation_sid: str, sid: str): **self._solution ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -279,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, @@ -300,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: @@ -317,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: """ @@ -337,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 @@ -364,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), @@ -394,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 @@ -427,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. @@ -442,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( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + 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( + { + "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 - 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[ + "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, @@ -472,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 @@ -490,6 +948,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: :param payload: Payload response from the API """ + return ParticipantInstance( self._version, payload, conversation_sid=self._solution["conversation_sid"] ) @@ -523,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 @@ -536,21 +995,12 @@ def create( attributes: Union[str, object] = values.unset, messaging_binding_projected_address: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> tuple: """ - Create the ParticipantInstance + Internal helper for create operation - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the 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 + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -572,15 +1022,59 @@ def create( } ) - 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 @@ -593,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. @@ -607,7 +1101,43 @@ async def create_async( :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. Communication mask for the Conversation participant with Identity. :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. - :returns: The created ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + instance = ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -629,14 +1159,103 @@ async def create_async( } ) - 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, @@ -687,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, @@ -706,6 +1375,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -732,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( @@ -740,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, @@ -764,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, @@ -791,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: """ @@ -806,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: """ @@ -818,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 b961b832a5..3140fd846c 100644 --- a/twilio/rest/conversations/v1/conversation/webhook.py +++ b/twilio/rest/conversations/v1/conversation/webhook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,8 +26,8 @@ class WebhookInstance(InstanceResource): class Method(object): - GET = "GET" - POST = "POST" + GET = "get" + POST = "post" class Target(object): WEBHOOK = "webhook" @@ -70,6 +71,7 @@ def __init__( "conversation_sid": conversation_sid, "sid": sid or self.sid, } + self._context: Optional[WebhookContext] = None @property @@ -106,6 +108,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WebhookInstance": """ Fetch the WebhookInstance @@ -124,6 +144,24 @@ async def fetch_async(self) -> "WebhookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, configuration_url: Union[str, object] = values.unset, @@ -178,6 +216,60 @@ async def update_async( configuration_flow_sid=configuration_flow_sid, ) + def update_with_http_info( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + + async def update_with_http_info_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -209,6 +301,20 @@ def __init__(self, version: Version, conversation_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WebhookInstance @@ -216,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: @@ -228,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: @@ -240,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: """ @@ -260,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, @@ -305,13 +491,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, @@ -319,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: @@ -336,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, @@ -351,13 +596,42 @@ async def update_async( "Configuration.FlowSid": configuration_flow_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, + 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, @@ -365,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 @@ -383,6 +691,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: :param payload: Payload response from the API """ + return WebhookInstance( self._version, payload, conversation_sid=self._solution["conversation_sid"] ) @@ -416,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, @@ -425,19 +734,12 @@ def create( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_replay_after: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Create the WebhookInstance + Internal helper for create operation - :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 + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -457,15 +759,51 @@ def create( ) headers = values.of({"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, + 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, @@ -474,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. @@ -486,7 +824,37 @@ async def create_async( :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default - :returns: The created WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + instance = WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -506,14 +874,87 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -564,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, @@ -583,6 +1074,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -609,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( @@ -617,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, @@ -641,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, @@ -668,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: """ @@ -683,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: """ @@ -695,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 c8cd78ab05..a1aabe7bdd 100644 --- a/twilio/rest/conversations/v1/credential.py +++ b/twilio/rest/conversations/v1/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, type: Union["CredentialInstance.PushType", object] = values.unset, @@ -180,6 +218,72 @@ async def update_async( secret=secret, ) + def update_with_http_info( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_with_http_info_async( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -207,6 +311,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -214,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: @@ -226,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: @@ -238,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: """ @@ -257,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, @@ -278,20 +478,14 @@ 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, @@ -303,16 +497,17 @@ def update( "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, @@ -323,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. @@ -335,80 +530,29 @@ async def update_async( :returns: The updated CredentialInstance """ - data = values.of( - { - "Type": type, - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": serialize.boolean_to_string(sandbox), - "ApiKey": api_key, - "Secret": secret, - } - ) - - 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. @@ -418,7 +562,35 @@ def create( :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. - :returns: The created CredentialInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -432,17 +604,19 @@ def create( "Secret": secret, } ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - payload = self._version.create( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return CredentialInstance(self._version, payload) - - async def create_async( + 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, @@ -451,7 +625,157 @@ 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. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + payload, _, _ = await self._update_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def _create( + self, + type: "CredentialInstance.PushType", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + type: "CredentialInstance.PushType", + friendly_name: Union[str, object] = values.unset, + 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. @@ -463,6 +787,68 @@ async def create_async( :returns: The created CredentialInstance """ + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + self, + type: "CredentialInstance.PushType", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "CredentialInstance.PushType", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -477,12 +863,83 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -533,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, @@ -552,6 +1059,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -578,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( @@ -586,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, @@ -610,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( @@ -637,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 7413047152..9d6fc2566b 100644 --- a/twilio/rest/conversations/v1/participant_conversation.py +++ b/twilio/rest/conversations/v1/participant_conversation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -104,6 +105,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantConversationInstan :param payload: Payload response from the API """ + return ParticipantConversationInstance(self._version, payload) def __repr__(self) -> str: @@ -190,6 +192,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, address=address, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, address=address, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, identity: Union[str, object] = values.unset, @@ -213,6 +275,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -245,6 +308,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -255,6 +319,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, identity: Union[str, object] = values.unset, @@ -285,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( @@ -318,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 301063800a..f0e9160bf5 100644 --- a/twilio/rest/conversations/v1/role.py +++ b/twilio/rest/conversations/v1/role.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RoleContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoleInstance": """ Fetch the RoleInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "RoleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, permission: List[str]) -> "RoleInstance": """ Update the RoleInstance @@ -139,6 +177,30 @@ async def update_async(self, permission: List[str]) -> "RoleInstance": permission=permission, ) + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + permission=permission, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -166,6 +228,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Roles/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoleInstance @@ -173,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: @@ -185,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: @@ -197,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: """ @@ -216,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" + + 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, 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 @@ -290,6 +496,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: :param payload: Payload response from the API """ + return RoleInstance(self._version, payload) def __repr__(self) -> str: @@ -314,17 +521,14 @@ def __init__(self, version: Version): self._uri = "/Roles" - def create( + def _create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> tuple: """ - Create the RoleInstance - - :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`. + Internal helper for create operation - :returns: The created RoleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -336,17 +540,19 @@ def create( ) headers = values.of({"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 RoleInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] ) -> RoleInstance: """ - Asynchronously create the RoleInstance + Create the RoleInstance :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. :param type: @@ -354,6 +560,38 @@ async def create_async( :returns: The created RoleInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + return RoleInstance(self._version, payload) + + def create_with_http_info( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Create the RoleInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -364,12 +602,49 @@ async def create_async( ) headers = values.of({"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, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance(self._version, payload) + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -420,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, @@ -439,6 +764,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -465,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( @@ -473,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, @@ -497,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( @@ -524,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 a06afa2f77..e4e33fc15e 100644 --- a/twilio/rest/conversations/v1/service/__init__.py +++ b/twilio/rest/conversations/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,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, ) @@ -61,6 +65,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -96,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 @@ -114,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: """ @@ -135,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: """ @@ -186,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 @@ -197,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: @@ -209,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: @@ -221,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: """ @@ -240,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: @@ -288,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: """ @@ -342,6 +501,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -366,13 +526,12 @@ def __init__(self, version: Version): self._uri = "/Services" - def create(self, friendly_name: str) -> ServiceInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the ServiceInstance - - :param friendly_name: The human-readable name of this service, limited to 256 characters. Optional. + Internal helper for create operation - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -382,19 +541,43 @@ def create(self, friendly_name: str) -> ServiceInstance: ) headers = values.of({"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, 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( @@ -404,12 +587,39 @@ async def create_async(self, friendly_name: str) -> ServiceInstance: ) headers = values.of({"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, 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, @@ -460,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, @@ -479,6 +739,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -505,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( @@ -513,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, @@ -537,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( @@ -564,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 6e66844490..095e307625 100644 --- a/twilio/rest/conversations/v1/service/binding.py +++ b/twilio/rest/conversations/v1/service/binding.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -28,6 +29,7 @@ class BindingType(object): APN = "apn" GCM = "gcm" FCM = "fcm" + TWILSOCK = "twilsock" """ :ivar sid: A 34 character string that uniquely identifies this resource. @@ -74,6 +76,7 @@ def __init__( "chat_service_sid": chat_service_sid, "sid": sid or self.sid, } + self._context: Optional[BindingContext] = None @property @@ -110,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "BindingInstance": """ Fetch the BindingInstance @@ -128,6 +149,24 @@ async def fetch_async(self) -> "BindingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -159,6 +198,20 @@ def __init__(self, version: Version, chat_service_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the BindingInstance @@ -166,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: @@ -178,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: @@ -190,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: """ @@ -210,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: """ @@ -241,6 +378,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: :param payload: Payload response from the API """ + return BindingInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) @@ -285,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 @@ -316,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 @@ -334,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, @@ -346,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 @@ -357,6 +555,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -378,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 @@ -389,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( @@ -399,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, @@ -411,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 @@ -429,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, @@ -444,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 @@ -462,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: """ @@ -477,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: """ @@ -489,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 9ca23a435f..4cdc9de636 100644 --- a/twilio/rest/conversations/v1/service/configuration/__init__.py +++ b/twilio/rest/conversations/v1/service/configuration/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,6 +59,7 @@ def __init__( self._solution = { "chat_service_sid": chat_service_sid, } + self._context: Optional[ConfigurationContext] = None @property @@ -93,6 +95,24 @@ async def fetch_async(self) -> "ConfigurationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, default_conversation_creator_role_sid: Union[str, object] = values.unset, @@ -141,6 +161,54 @@ async def update_async( reachability_enabled=reachability_enabled, ) + def update_with_http_info( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConfigurationInstance with HTTP info + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) + + async def update_with_http_info_async( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance with HTTP info + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -170,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 @@ -177,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: """ @@ -196,35 +306,42 @@ 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 - - :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`. + Internal helper for update operation - :returns: The updated ConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "DefaultConversationCreatorRoleSid": default_conversation_creator_role_sid, @@ -235,34 +352,85 @@ 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, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ConfigurationInstance: + """ + Update the ConfigurationInstance + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = self._update( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) return ConfigurationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - async def update_async( + def update_with_http_info( self, default_conversation_creator_role_sid: Union[str, object] = values.unset, default_conversation_role_sid: Union[str, object] = values.unset, default_chat_service_role_sid: Union[str, object] = values.unset, reachability_enabled: Union[bool, object] = values.unset, - ) -> ConfigurationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ConfigurationInstance + Update the ConfigurationInstance and return response metadata :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. - :returns: The updated ConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) + instance = ConfigurationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "DefaultConversationCreatorRoleSid": default_conversation_creator_role_sid, @@ -273,17 +441,71 @@ async def update_async( ), } ) + 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, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: The updated ConfigurationInstance + """ + payload, _, _ = await self._update_async( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) return ConfigurationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) + async def update_with_http_info_async( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance and return response metadata + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) + instance = ConfigurationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/conversations/v1/service/configuration/notification.py b/twilio/rest/conversations/v1/service/configuration/notification.py index 2dee2d4d29..e646dbe7b9 100644 --- a/twilio/rest/conversations/v1/service/configuration/notification.py +++ b/twilio/rest/conversations/v1/service/configuration/notification.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( self._solution = { "chat_service_sid": chat_service_sid, } + self._context: Optional[NotificationContext] = None @property @@ -86,6 +88,24 @@ async def fetch_async(self) -> "NotificationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NotificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, log_enabled: Union[bool, object] = values.unset, @@ -188,6 +208,108 @@ async def update_async( new_message_with_media_template=new_message_with_media_template, ) + def update_with_http_info( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the NotificationInstance with HTTP info + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) + + async def update_with_http_info_async( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the NotificationInstance with HTTP info + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -217,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 @@ -224,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: """ @@ -243,19 +407,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, + 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( + def _update( self, log_enabled: Union[bool, object] = values.unset, new_message_enabled: Union[bool, object] = values.unset, @@ -270,26 +444,14 @@ def update( removed_from_conversation_sound: Union[str, object] = values.unset, new_message_with_media_enabled: Union[bool, object] = values.unset, new_message_with_media_template: Union[str, object] = values.unset, - ) -> NotificationInstance: + ) -> tuple: """ - Update the NotificationInstance + Internal helper for update operation - :param log_enabled: Weather the notification logging is enabled. - :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. - :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. - :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. - :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. - :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. - :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. - :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. - :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. - :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. - :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. - :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. - :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. - - :returns: The updated NotificationInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "LogEnabled": serialize.boolean_to_string(log_enabled), @@ -315,18 +477,71 @@ def update( "NewMessage.WithMedia.Template": new_message_with_media_template, } ) + 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, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> NotificationInstance: + """ + Update the NotificationInstance + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: The updated NotificationInstance + """ + payload, _, _ = self._update( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) return NotificationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - async def update_async( + def update_with_http_info( self, log_enabled: Union[bool, object] = values.unset, new_message_enabled: Union[bool, object] = values.unset, @@ -341,9 +556,9 @@ async def update_async( removed_from_conversation_sound: Union[str, object] = values.unset, new_message_with_media_enabled: Union[bool, object] = values.unset, new_message_with_media_template: Union[str, object] = values.unset, - ) -> NotificationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the NotificationInstance + Update the NotificationInstance and return response metadata :param log_enabled: Weather the notification logging is enabled. :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. @@ -359,8 +574,51 @@ async def update_async( :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. - :returns: The updated NotificationInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._update( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) + instance = NotificationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "LogEnabled": serialize.boolean_to_string(log_enabled), @@ -386,17 +644,125 @@ async def update_async( "NewMessage.WithMedia.Template": new_message_with_media_template, } ) + 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, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> NotificationInstance: + """ + Asynchronous coroutine to update the NotificationInstance + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: The updated NotificationInstance + """ + payload, _, _ = await self._update_async( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) return NotificationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) + async def update_with_http_info_async( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the NotificationInstance and return response metadata + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) + instance = NotificationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/conversations/v1/service/configuration/webhook.py b/twilio/rest/conversations/v1/service/configuration/webhook.py index aa4015361f..eee7e3f74e 100644 --- a/twilio/rest/conversations/v1/service/configuration/webhook.py +++ b/twilio/rest/conversations/v1/service/configuration/webhook.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,7 @@ def __init__( self._solution = { "chat_service_sid": chat_service_sid, } + self._context: Optional[WebhookContext] = None @property @@ -87,6 +89,24 @@ async def fetch_async(self) -> "WebhookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, pre_webhook_url: Union[str, object] = values.unset, @@ -135,6 +155,54 @@ async def update_async( method=method, ) + def update_with_http_info( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + + async def update_with_http_info_async( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -164,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 @@ -171,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: """ @@ -190,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, @@ -219,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, @@ -227,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( @@ -255,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: """ diff --git a/twilio/rest/conversations/v1/service/conversation/__init__.py b/twilio/rest/conversations/v1/service/conversation/__init__.py index 139bdcb5ca..0dcfd00023 100644 --- a/twilio/rest/conversations/v1/service/conversation/__init__.py +++ b/twilio/rest/conversations/v1/service/conversation/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -33,6 +34,7 @@ class State(object): INACTIVE = "inactive" ACTIVE = "active" CLOSED = "closed" + INITIALIZING = "initializing" class WebhookEnabledType(object): TRUE = "true" @@ -87,6 +89,7 @@ def __init__( "chat_service_sid": chat_service_sid, "sid": sid or self.sid, } + self._context: Optional[ConversationContext] = None @property @@ -139,6 +142,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "ConversationInstance": """ Fetch the ConversationInstance @@ -157,6 +194,24 @@ async def fetch_async(self) -> "ConversationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -257,6 +312,106 @@ async def update_async( bindings_email_name=bindings_email_name, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConversationInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + @property def messages(self) -> MessageList: """ @@ -313,6 +468,30 @@ def __init__(self, version: Version, chat_service_sid: str, sid: str): self._participants: Optional[ParticipantList] = None self._webhooks: Optional[WebhookList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -326,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, @@ -347,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: @@ -364,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: """ @@ -384,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 @@ -413,25 +696,14 @@ def update( unique_name: Union[str, object] = values.unset, bindings_email_address: Union[str, object] = values.unset, bindings_email_name: Union[str, object] = values.unset, - ) -> ConversationInstance: + ) -> tuple: """ - Update the ConversationInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. - :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. - :param state: - :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. - :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. - :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. - :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + Internal helper for update operation - :returns: The updated ConversationInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -447,24 +719,26 @@ def update( "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 @@ -482,7 +756,7 @@ async def update_async( bindings_email_name: Union[str, object] = values.unset, ) -> ConversationInstance: """ - Asynchronous coroutine to update the ConversationInstance + Update the ConversationInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. @@ -499,8 +773,110 @@ async def update_async( :returns: The updated ConversationInstance """ - data = values.of( - { + 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), @@ -514,16 +890,74 @@ async def update_async( "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 - 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, @@ -531,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: """ @@ -588,6 +1079,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: :param payload: Payload response from the API """ + return ConversationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) @@ -621,6 +1113,60 @@ def __init__(self, version: Version, chat_service_sid: str): **self._solution ) + def _create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, x_twilio_webhook_enabled: Union[ @@ -656,6 +1202,101 @@ def create( :returns: The created ConversationInstance """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + date_created=date_created, + date_updated=date_updated, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + return ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def create_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ConversationInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + date_created=date_created, + date_updated=date_updated, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + instance = ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -679,15 +1320,68 @@ def create( } ) - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Asynchronously create the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :returns: The created ConversationInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + date_created=date_created, + date_updated=date_updated, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) return ConversationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - async def create_async( + async def create_with_http_info_async( self, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -703,9 +1397,9 @@ async def create_async( timers_closed: Union[str, object] = values.unset, bindings_email_address: Union[str, object] = values.unset, bindings_email_name: Union[str, object] = values.unset, - ) -> ConversationInstance: + ) -> ApiResponse: """ - Asynchronously create the ConversationInstance + Asynchronously create the ConversationInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. @@ -720,38 +1414,26 @@ async def create_async( :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. - :returns: The created ConversationInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "Attributes": attributes, - "MessagingServiceSid": messaging_service_sid, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "State": state, - "Timers.Inactive": timers_inactive, - "Timers.Closed": timers_closed, - "Bindings.Email.Address": bindings_email_address, - "Bindings.Email.Name": bindings_email_name, - } - ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - "Content-Type": "application/x-www-form-urlencoded", - } - ) - - 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, @@ -825,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, @@ -850,6 +1602,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( start_date=start_date, @@ -885,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( @@ -896,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, @@ -929,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, @@ -965,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: """ @@ -980,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: """ @@ -992,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 32f480bc59..6c4e26231b 100644 --- a/twilio/rest/conversations/v1/service/conversation/message/__init__.py +++ b/twilio/rest/conversations/v1/service/conversation/message/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -90,6 +91,7 @@ def __init__( "conversation_sid": conversation_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -143,6 +145,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -161,6 +197,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -231,6 +285,76 @@ async def update_async( subject=subject, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :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 def delivery_receipts(self) -> DeliveryReceiptList: """ @@ -275,6 +399,30 @@ def __init__( self._delivery_receipts: Optional[DeliveryReceiptList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -288,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, @@ -309,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: @@ -326,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: """ @@ -347,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 @@ -372,20 +626,14 @@ def update( date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, subject: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Update the MessageInstance - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param author: The channel specific identifier of the message's author. Defaults to `system`. - :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. - :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param subject: The subject of the message, can be up to 256 characters long. + Internal helper for update operation - :returns: The updated MessageInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Author": author, @@ -396,25 +644,26 @@ def update( "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 @@ -427,7 +676,7 @@ async def update_async( subject: Union[str, object] = values.unset, ) -> MessageInstance: """ - Asynchronous coroutine to update the MessageInstance + Update the MessageInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param author: The channel specific identifier of the message's author. Defaults to `system`. @@ -439,26 +688,15 @@ async def update_async( :returns: The updated MessageInstance """ - data = values.of( - { - "Author": author, - "Body": body, - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "Attributes": attributes, - "Subject": subject, - } - ) - headers = values.of( - { - "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, @@ -467,15 +705,191 @@ async def update_async( sid=self._solution["sid"], ) - @property - def delivery_receipts(self) -> DeliveryReceiptList: - """ - Access the delivery_receipts - """ - if self._delivery_receipts is None: - self._delivery_receipts = DeliveryReceiptList( - self._version, - self._solution["chat_service_sid"], + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance and return response metadata + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :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"], self._solution["sid"], ) @@ -499,6 +913,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, @@ -537,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 @@ -551,22 +966,12 @@ def create( content_sid: Union[str, object] = values.unset, content_variables: Union[str, object] = values.unset, subject: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance + Internal helper for create operation - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param author: The channel specific identifier of the message's author. Defaults to `system`. - :param body: The content of the message, can be up to 1,600 characters long. - :param date_created: The date that this resource was created. - :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. - :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. - :param media_sid: The Media SID to be attached to the new Message. - :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. - :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. - :param subject: The subject of the message, can be up to 256 characters long. - - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -589,10 +994,57 @@ def create( } ) - 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, @@ -600,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 @@ -614,9 +1066,9 @@ async def create_async( content_sid: Union[str, object] = values.unset, content_variables: Union[str, object] = values.unset, subject: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> ApiResponse: """ - Asynchronously create the MessageInstance + Create the MessageInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param author: The channel specific identifier of the message's author. Defaults to `system`. @@ -629,7 +1081,48 @@ async def create_async( :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( @@ -652,10 +1145,57 @@ async def create_async( } ) - 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, @@ -663,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, @@ -717,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, @@ -738,6 +1385,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -767,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( @@ -776,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, @@ -803,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, @@ -833,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: """ @@ -848,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: """ @@ -860,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 b9bf8a70c8..d729edcd52 100644 --- a/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py +++ b/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -82,6 +83,7 @@ def __init__( "message_sid": message_sid, "sid": sid or self.sid, } + self._context: Optional[DeliveryReceiptContext] = None @property @@ -120,6 +122,24 @@ async def fetch_async(self) -> "DeliveryReceiptInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeliveryReceiptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -162,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 @@ -169,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"], @@ -183,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: """ @@ -191,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"], @@ -205,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: """ @@ -224,6 +302,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DeliveryReceiptInstance: :param payload: Payload response from the API """ + return DeliveryReceiptInstance( self._version, payload, @@ -321,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, @@ -340,6 +469,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -366,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( @@ -374,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, @@ -398,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, @@ -425,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: """ @@ -440,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: """ @@ -452,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 530bce26fc..960f36fd16 100644 --- a/twilio/rest/conversations/v1/service/conversation/participant.py +++ b/twilio/rest/conversations/v1/service/conversation/participant.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -81,6 +82,7 @@ def __init__( "conversation_sid": conversation_sid, "sid": sid or self.sid, } + self._context: Optional[ParticipantContext] = None @property @@ -134,6 +136,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "ParticipantInstance": """ Fetch the ParticipantInstance @@ -152,6 +188,24 @@ async def fetch_async(self) -> "ParticipantInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -240,6 +294,94 @@ async def update_async( last_read_timestamp=last_read_timestamp, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + identity=identity, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + identity=identity, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -275,6 +417,30 @@ def __init__( **self._solution ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -288,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, @@ -309,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: @@ -326,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: """ @@ -347,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 @@ -375,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 on which this resource was created. - :param date_updated: The date on which this resource was last updated. - :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. - :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. - :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. - :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. - :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. - :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. - :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + Internal helper for update operation - :returns: The updated ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "DateCreated": serialize.iso8601_datetime(date_created), @@ -405,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 @@ -439,7 +703,7 @@ async def update_async( last_read_timestamp: Union[str, object] = values.unset, ) -> ParticipantInstance: """ - Asynchronous coroutine to update the ParticipantInstance + Update the ParticipantInstance :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param date_created: The date on which this resource was created. @@ -454,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, - } - ) - headers = values.of( + payload, _, _ = self._update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + identity=identity, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + 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, @@ -485,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 @@ -503,6 +965,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: :param payload: Payload response from the API """ + return ParticipantInstance( self._version, payload, @@ -541,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 @@ -554,21 +1017,12 @@ def create( attributes: Union[str, object] = values.unset, messaging_binding_projected_address: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> tuple: """ - Create the ParticipantInstance - - :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. + Internal helper for create operation - :returns: The created ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -590,10 +1044,54 @@ def create( } ) - 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, @@ -601,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 @@ -614,9 +1112,9 @@ async def create_async( attributes: Union[str, object] = values.unset, messaging_binding_projected_address: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> ApiResponse: """ - Asynchronously create the ParticipantInstance + Create the ParticipantInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. @@ -628,7 +1126,46 @@ async def create_async( :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. - :returns: The created ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + identity=identity, + messaging_binding_address=messaging_binding_address, + messaging_binding_proxy_address=messaging_binding_proxy_address, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_binding_projected_address=messaging_binding_projected_address, + role_sid=role_sid, + ) + instance = ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -650,10 +1187,54 @@ async def create_async( } ) - 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, @@ -661,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, @@ -711,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, @@ -730,6 +1409,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -756,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( @@ -764,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, @@ -788,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, @@ -815,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: """ @@ -830,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: """ @@ -842,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 327dc9f024..d95e4d364e 100644 --- a/twilio/rest/conversations/v1/service/conversation/webhook.py +++ b/twilio/rest/conversations/v1/service/conversation/webhook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,8 +26,8 @@ class WebhookInstance(InstanceResource): class Method(object): - GET = "GET" - POST = "POST" + GET = "get" + POST = "post" class Target(object): WEBHOOK = "webhook" @@ -74,6 +75,7 @@ def __init__( "conversation_sid": conversation_sid, "sid": sid or self.sid, } + self._context: Optional[WebhookContext] = None @property @@ -111,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WebhookInstance": """ Fetch the WebhookInstance @@ -129,6 +149,24 @@ async def fetch_async(self) -> "WebhookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, configuration_url: Union[str, object] = values.unset, @@ -183,6 +221,60 @@ async def update_async( configuration_flow_sid=configuration_flow_sid, ) + def update_with_http_info( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + + async def update_with_http_info_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -218,6 +310,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WebhookInstance @@ -225,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: @@ -237,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: @@ -249,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: """ @@ -270,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, @@ -316,13 +504,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, @@ -331,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: @@ -348,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, @@ -363,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, @@ -378,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 @@ -396,6 +708,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: :param payload: Payload response from the API """ + return WebhookInstance( self._version, payload, @@ -434,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, @@ -443,19 +756,12 @@ def create( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_replay_after: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Create the WebhookInstance + Internal helper for create operation - :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 + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -475,10 +781,46 @@ def create( ) headers = values.of({"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, + 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, @@ -486,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, @@ -495,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. @@ -507,7 +849,40 @@ async def create_async( :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default - :returns: The created WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + target=target, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_replay_after=configuration_replay_after, + ) + instance = WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -527,10 +902,46 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -538,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, @@ -588,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, @@ -607,6 +1108,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -633,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( @@ -641,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, @@ -665,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, @@ -692,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: """ @@ -707,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: """ @@ -719,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 2c3bebcc1e..790e753f20 100644 --- a/twilio/rest/conversations/v1/service/participant_conversation.py +++ b/twilio/rest/conversations/v1/service/participant_conversation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -112,6 +113,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantConversationInstan :param payload: Payload response from the API """ + return ParticipantConversationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) @@ -207,6 +209,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + identity=identity, address=address, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + identity=identity, address=address, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, identity: Union[str, object] = values.unset, @@ -230,6 +292,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -262,6 +325,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -272,6 +336,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ParticipantConversationInstance and returns headers from first page + + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, identity: Union[str, object] = values.unset, @@ -302,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, @@ -335,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: """ @@ -350,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: """ @@ -362,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 170512a2b2..f7373513a0 100644 --- a/twilio/rest/conversations/v1/service/role.py +++ b/twilio/rest/conversations/v1/service/role.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "chat_service_sid": chat_service_sid, "sid": sid or self.sid, } + self._context: Optional[RoleContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoleInstance": """ Fetch the RoleInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "RoleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, permission: List[str]) -> "RoleInstance": """ Update the RoleInstance @@ -145,6 +183,30 @@ async def update_async(self, permission: List[str]) -> "RoleInstance": permission=permission, ) + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + permission=permission, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -174,6 +236,20 @@ def __init__(self, version: Version, chat_service_sid: str, sid: str): } self._uri = "/Services/{chat_service_sid}/Roles/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoleInstance @@ -181,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: @@ -193,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: @@ -205,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: """ @@ -225,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, @@ -238,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({}) + + 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, 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, @@ -265,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, @@ -292,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 @@ -310,6 +528,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) @@ -341,17 +560,14 @@ def __init__(self, version: Version, chat_service_sid: str): } self._uri = "/Services/{chat_service_sid}/Roles".format(**self._solution) - def create( + def _create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> tuple: """ - Create the RoleInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. - :param type: - :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. - - :returns: The created RoleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -363,25 +579,61 @@ def create( ) headers = values.of({"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, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> ApiResponse: """ - Asynchronously create the RoleInstance + Create the RoleInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. :param type: :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. - :returns: The created RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -393,14 +645,53 @@ async def create_async( ) headers = values.of({"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, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -451,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, @@ -470,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -496,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( @@ -504,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, @@ -528,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, @@ -555,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: """ @@ -570,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: """ @@ -582,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 4d4df0398d..55e16cd848 100644 --- a/twilio/rest/conversations/v1/service/user/__init__.py +++ b/twilio/rest/conversations/v1/service/user/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -78,6 +79,7 @@ def __init__( "chat_service_sid": chat_service_sid, "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -130,6 +132,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "UserInstance": """ Fetch the UserInstance @@ -148,6 +184,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -200,6 +254,58 @@ async def update_async( role_sid=role_sid, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + @property def user_conversations(self) -> UserConversationList: """ @@ -238,6 +344,30 @@ def __init__(self, version: Version, chat_service_sid: str, sid: str): self._user_conversations: Optional[UserConversationList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -251,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, @@ -272,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: @@ -289,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: """ @@ -309,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 @@ -330,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 + Internal helper for update operation - :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: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -348,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 + + 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[ + "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, @@ -365,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 @@ -373,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, @@ -391,22 +686,89 @@ 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 + + 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 ) - payload = await self._version.update_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. - return UserInstance( + :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: @@ -439,6 +801,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserInstance: :param payload: Payload response from the API """ + return UserInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) @@ -470,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[ @@ -479,17 +842,12 @@ def create( friendly_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Create the UserInstance - - :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: The string that you assigned to describe the resource. - :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. - :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + Internal helper for create operation - :returns: The created UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -507,15 +865,47 @@ def create( } ) - 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[ @@ -524,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 @@ -534,7 +924,35 @@ async def create_async( :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. - :returns: The created UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -552,14 +970,79 @@ async def create_async( } ) - 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, @@ -610,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, @@ -629,6 +1162,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -655,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( @@ -663,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, @@ -687,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, @@ -714,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: """ @@ -729,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: """ @@ -741,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 7a836505b9..7a05c5fc73 100644 --- a/twilio/rest/conversations/v1/service/user/user_conversation.py +++ b/twilio/rest/conversations/v1/service/user/user_conversation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -100,6 +101,7 @@ def __init__( "user_sid": user_sid, "conversation_sid": conversation_sid or self.conversation_sid, } + self._context: Optional[UserConversationContext] = None @property @@ -137,6 +139,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserConversationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserConversationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserConversationInstance": """ Fetch the UserConversationInstance @@ -155,6 +175,24 @@ async def fetch_async(self) -> "UserConversationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, notification_level: Union[ @@ -201,6 +239,52 @@ async def update_async( last_read_message_index=last_read_message_index, ) + def update_with_http_info( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserConversationInstance with HTTP info + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + async def update_with_http_info_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserConversationInstance with HTTP info + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -240,6 +324,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserConversationInstance @@ -247,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: @@ -259,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: @@ -271,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: """ @@ -292,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 - - :param notification_level: - :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. - :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + Internal helper for update operation - :returns: The updated UserConversationInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "NotificationLevel": notification_level, @@ -330,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, @@ -345,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, @@ -369,13 +605,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, @@ -384,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 @@ -402,6 +694,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserConversationInstance: :param payload: Payload response from the API """ + return UserConversationInstance( self._version, payload, @@ -492,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, @@ -511,6 +854,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -537,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( @@ -545,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, @@ -569,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, @@ -596,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: """ @@ -611,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: """ @@ -623,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 a05deeda43..b149577147 100644 --- a/twilio/rest/conversations/v1/user/__init__.py +++ b/twilio/rest/conversations/v1/user/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -71,6 +72,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -122,6 +124,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "UserInstance": """ Fetch the UserInstance @@ -140,6 +176,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -192,6 +246,58 @@ async def update_async( role_sid=role_sid, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + @property def user_conversations(self) -> UserConversationList: """ @@ -228,6 +334,30 @@ def __init__(self, version: Version, sid: str): self._user_conversations: Optional[UserConversationList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -241,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, @@ -262,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: @@ -279,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: """ @@ -298,17 +520,69 @@ 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, + 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 helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + 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 self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) def update( self, @@ -329,6 +603,58 @@ def update( :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, @@ -336,18 +662,25 @@ 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 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"]) - async def update_async( self, x_twilio_webhook_enabled: Union[ @@ -358,33 +691,50 @@ async def update_async( role_sid: Union[str, object] = values.unset, ) -> UserInstance: """ - Asynchronous coroutine to update the UserInstance + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + payload, _, _ = await self._update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance and return response metadata :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header :param friendly_name: The string that you assigned to describe the resource. :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. - :returns: The updated UserInstance + :returns: ApiResponse with instance, status code, and headers """ - data = values.of( - { - "FriendlyName": friendly_name, - "Attributes": attributes, - "RoleSid": role_sid, - } - ) - 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, 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, ) - - return UserInstance(self._version, payload, sid=self._solution["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: @@ -416,6 +766,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserInstance: :param payload: Payload response from the API """ + return UserInstance(self._version, payload) def __repr__(self) -> str: @@ -440,7 +791,7 @@ def __init__(self, version: Version): self._uri = "/Users" - def create( + def _create( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -449,17 +800,12 @@ def create( friendly_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, role_sid: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Create the UserInstance - - :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: The string that you assigned to describe the resource. - :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. - :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + Internal helper for create operation - :returns: The created UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -477,13 +823,15 @@ def create( } ) - 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[ @@ -494,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 @@ -504,6 +852,62 @@ async def create_async( :returns: The created UserInstance """ + payload, _, _ = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + return UserInstance(self._version, payload) + + def create_with_http_info( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the UserInstance and return response metadata + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + instance = UserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -520,12 +924,75 @@ async def create_async( } ) - 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, @@ -576,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, @@ -595,6 +1112,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -621,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( @@ -629,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, @@ -653,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( @@ -680,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 e162441151..c6dd85ac39 100644 --- a/twilio/rest/conversations/v1/user/user_conversation.py +++ b/twilio/rest/conversations/v1/user/user_conversation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -98,6 +99,7 @@ def __init__( "user_sid": user_sid, "conversation_sid": conversation_sid or self.conversation_sid, } + self._context: Optional[UserConversationContext] = None @property @@ -134,6 +136,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserConversationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserConversationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserConversationInstance": """ Fetch the UserConversationInstance @@ -152,6 +172,24 @@ async def fetch_async(self) -> "UserConversationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserConversationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, notification_level: Union[ @@ -198,6 +236,52 @@ async def update_async( last_read_message_index=last_read_message_index, ) + def update_with_http_info( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserConversationInstance with HTTP info + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + async def update_with_http_info_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserConversationInstance with HTTP info + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -229,6 +313,20 @@ def __init__(self, version: Version, user_sid: str, conversation_sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserConversationInstance @@ -236,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: @@ -248,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: @@ -260,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: """ @@ -280,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 - - :param notification_level: - :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. - :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + Internal helper for update operation - :returns: The updated UserConversationInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "NotificationLevel": notification_level, @@ -317,13 +497,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, @@ -331,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, @@ -355,13 +588,38 @@ async def update_async( "LastReadMessageIndex": last_read_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, + 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, @@ -369,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 @@ -387,6 +675,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserConversationInstance: :param payload: Payload response from the API """ + return UserConversationInstance( self._version, payload, user_sid=self._solution["user_sid"] ) @@ -468,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, @@ -487,6 +826,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -513,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( @@ -521,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, @@ -545,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, @@ -572,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: """ @@ -587,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: """ @@ -599,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/v1/event_type.py b/twilio/rest/events/v1/event_type.py index a019a82a9e..d00ce94b1a 100644 --- a/twilio/rest/events/v1/event_type.py +++ b/twilio/rest/events/v1/event_type.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( self._solution = { "type": type or self.type, } + self._context: Optional[EventTypeContext] = None @property @@ -92,6 +94,24 @@ async def fetch_async(self) -> "EventTypeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EventTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EventTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -119,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 @@ -126,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: """ @@ -145,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: """ @@ -175,6 +247,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EventTypeInstance: :param payload: Payload response from the API """ + return EventTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -253,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, @@ -274,6 +403,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( schema_id=schema_id, @@ -303,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( @@ -312,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, @@ -339,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( @@ -369,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 c3b6593c03..5d26d6f6ab 100644 --- a/twilio/rest/events/v1/schema/__init__.py +++ b/twilio/rest/events/v1/schema/__init__.py @@ -14,7 +14,8 @@ 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 @@ -50,6 +51,7 @@ def __init__( self._solution = { "id": id or self.id, } + self._context: Optional[SchemaContext] = None @property @@ -85,6 +87,24 @@ async def fetch_async(self) -> "SchemaInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SchemaInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SchemaInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def versions(self) -> SchemaVersionList: """ @@ -121,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 @@ -128,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: """ @@ -147,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: diff --git a/twilio/rest/events/v1/schema/schema_version.py b/twilio/rest/events/v1/schema/schema_version.py index 3557cb2935..d846590c83 100644 --- a/twilio/rest/events/v1/schema/schema_version.py +++ b/twilio/rest/events/v1/schema/schema_version.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -54,6 +55,7 @@ def __init__( "id": id, "schema_version": schema_version or self.schema_version, } + self._context: Optional[SchemaVersionContext] = None @property @@ -90,6 +92,24 @@ async def fetch_async(self) -> "SchemaVersionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SchemaVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SchemaVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -119,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 @@ -126,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: """ @@ -146,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: """ @@ -177,6 +251,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SchemaVersionInstance: :param payload: Payload response from the API """ + return SchemaVersionInstance(self._version, payload, id=self._solution["id"]) def __repr__(self) -> str: @@ -256,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, @@ -275,6 +400,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -301,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( @@ -309,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, @@ -333,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, @@ -360,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: """ @@ -375,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: """ @@ -387,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 9098c51bd7..6bed98c16b 100644 --- a/twilio/rest/events/v1/sink/__init__.py +++ b/twilio/rest/events/v1/sink/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -30,6 +31,7 @@ class SinkType(object): KINESIS = "kinesis" WEBHOOK = "webhook" SEGMENT = "segment" + EMAIL = "email" class Status(object): INITIALIZED = "initialized" @@ -73,6 +75,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SinkContext] = None @property @@ -108,6 +111,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SinkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SinkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SinkInstance": """ Fetch the SinkInstance @@ -126,6 +147,24 @@ async def fetch_async(self) -> "SinkInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SinkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SinkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, description: str) -> "SinkInstance": """ Update the SinkInstance @@ -150,6 +189,30 @@ async def update_async(self, description: str) -> "SinkInstance": description=description, ) + def update_with_http_info(self, description: str) -> ApiResponse: + """ + Update the SinkInstance with HTTP info + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + description=description, + ) + + async def update_with_http_info_async(self, description: str) -> ApiResponse: + """ + Asynchronous coroutine to update the SinkInstance with HTTP info + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + description=description, + ) + @property def sink_test(self) -> SinkTestList: """ @@ -194,6 +257,20 @@ def __init__(self, version: Version, sid: str): self._sink_test: Optional[SinkTestList] = None self._sink_validate: Optional[SinkValidateList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SinkInstance @@ -201,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: @@ -213,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: @@ -225,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: """ @@ -244,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({}) + + 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, 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({}) - 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, 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: """ @@ -342,6 +551,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SinkInstance: :param payload: Payload response from the API """ + return SinkInstance(self._version, payload) def __repr__(self) -> str: @@ -366,20 +576,17 @@ def __init__(self, version: Version): self._uri = "/Sinks" - def create( + def _create( self, description: str, sink_configuration: object, sink_type: "SinkInstance.SinkType", - ) -> SinkInstance: + ) -> tuple: """ - Create the SinkInstance - - :param description: A human readable description for the Sink **This value should not contain PII.** - :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. - :param sink_type: + Internal helper for create operation - :returns: The created SinkInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -391,20 +598,22 @@ def create( ) headers = values.of({"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 SinkInstance(self._version, payload) - - async def create_async( + def create( self, description: str, sink_configuration: object, sink_type: "SinkInstance.SinkType", ) -> SinkInstance: """ - Asynchronously create the SinkInstance + Create the SinkInstance :param description: A human readable description for the Sink **This value should not contain PII.** :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. @@ -412,6 +621,48 @@ async def create_async( :returns: The created SinkInstance """ + payload, _, _ = self._create( + description=description, + sink_configuration=sink_configuration, + sink_type=sink_type, + ) + return SinkInstance(self._version, payload) + + def create_with_http_info( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> ApiResponse: + """ + Create the SinkInstance and return response metadata + + :param description: A human readable description for the Sink **This value should not contain PII.** + :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. + :param sink_type: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + description=description, + sink_configuration=sink_configuration, + sink_type=sink_type, + ) + instance = SinkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -422,12 +673,59 @@ async def create_async( ) headers = values.of({"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, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> SinkInstance: + """ + Asynchronously create the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. + :param sink_type: + + :returns: The created SinkInstance + """ + payload, _, _ = await self._create_async( + description=description, + sink_configuration=sink_configuration, + sink_type=sink_type, + ) return SinkInstance(self._version, payload) + async def create_with_http_info_async( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> ApiResponse: + """ + Asynchronously create the SinkInstance and return response metadata + + :param description: A human readable description for the Sink **This value should not contain PII.** + :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. + :param sink_type: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + description=description, + sink_configuration=sink_configuration, + sink_type=sink_type, + ) + instance = SinkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, in_use: Union[bool, object] = values.unset, @@ -488,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, @@ -511,6 +869,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( in_use=in_use, @@ -543,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( @@ -553,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, @@ -583,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( @@ -616,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 150e7deabc..7d253b7536 100644 --- a/twilio/rest/events/v1/sink/sink_test.py +++ b/twilio/rest/events/v1/sink/sink_test.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,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,12 +86,35 @@ def create(self) -> SinkTestInstance: :returns: The created SinkTestInstance """ + payload, _, _ = self._create() + return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the SinkTestInstance and return response metadata + + + :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"}) - payload = self._version.create(method="POST", uri=self._uri, headers=headers) + headers["Accept"] = "application/json" - return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, headers=headers + ) async def create_async(self) -> SinkTestInstance: """ @@ -83,14 +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"]) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the SinkTestInstance and return response metadata - payload = await self._version.create_async( - method="POST", uri=self._uri, headers=headers - ) - 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 8c6565a007..aa7a169673 100644 --- a/twilio/rest/events/v1/sink/sink_validate.py +++ b/twilio/rest/events/v1/sink/sink_validate.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,13 +63,12 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Sinks/{sid}/Validate".format(**self._solution) - def create(self, test_id: str) -> SinkValidateInstance: + def _create(self, test_id: str) -> tuple: """ - Create the SinkValidateInstance + Internal helper for create operation - :param test_id: A 34 character string that uniquely identifies the test event for a Sink being validated. - - :returns: The created SinkValidateInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -78,19 +78,45 @@ def create(self, test_id: str) -> SinkValidateInstance: ) headers = values.of({"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, 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( @@ -100,12 +126,39 @@ async def create_async(self, test_id: str) -> SinkValidateInstance: ) headers = values.of({"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, 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 2f6d7e91a2..f494c773c9 100644 --- a/twilio/rest/events/v1/subscription/__init__.py +++ b/twilio/rest/events/v1/subscription/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SubscriptionContext] = None @property @@ -91,6 +93,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SubscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SubscriptionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SubscriptionInstance": """ Fetch the SubscriptionInstance @@ -109,40 +129,78 @@ async def fetch_async(self) -> "SubscriptionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscriptionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( - self, - description: Union[str, object] = values.unset, - sink_sid: Union[str, object] = values.unset, + self, description: Union[str, object] = values.unset ) -> "SubscriptionInstance": """ Update the SubscriptionInstance :param description: A human readable description for the Subscription. - :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. :returns: The updated SubscriptionInstance """ return self._proxy.update( description=description, - sink_sid=sink_sid, ) async def update_async( - self, - description: Union[str, object] = values.unset, - sink_sid: Union[str, object] = values.unset, + self, description: Union[str, object] = values.unset ) -> "SubscriptionInstance": """ Asynchronous coroutine to update the SubscriptionInstance :param description: A human readable description for the Subscription. - :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. :returns: The updated SubscriptionInstance """ return await self._proxy.update_async( description=description, - sink_sid=sink_sid, + ) + + def update_with_http_info( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the SubscriptionInstance with HTTP info + + :param description: A human readable description for the Subscription. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + description=description, + ) + + async def update_with_http_info_async( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SubscriptionInstance with HTTP info + + :param description: A human readable description for the Subscription. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + description=description, ) @property @@ -181,6 +239,20 @@ def __init__(self, version: Version, sid: str): self._subscribed_events: Optional[SubscribedEventList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SubscriptionInstance @@ -188,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: @@ -200,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: @@ -212,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: """ @@ -231,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: @@ -329,6 +535,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SubscriptionInstance: :param payload: Payload response from the API """ + return SubscriptionInstance(self._version, payload) def __repr__(self) -> str: @@ -353,17 +560,12 @@ def __init__(self, version: Version): self._uri = "/Subscriptions" - def create( - self, description: str, sink_sid: str, types: List[object] - ) -> SubscriptionInstance: + def _create(self, description: str, sink_sid: str, types: List[object]) -> tuple: """ - Create the SubscriptionInstance + Internal helper for create operation - :param description: A human readable description for the Subscription **This value should not contain PII.** - :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. - :param types: An array of objects containing the subscribed Event Types - - :returns: The created SubscriptionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -375,17 +577,19 @@ def create( ) headers = values.of({"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 SubscriptionInstance(self._version, payload) - - async def create_async( + def create( self, description: str, sink_sid: str, types: List[object] ) -> SubscriptionInstance: """ - Asynchronously create the SubscriptionInstance + Create the SubscriptionInstance :param description: A human readable description for the Subscription **This value should not contain PII.** :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. @@ -393,6 +597,38 @@ async def create_async( :returns: The created SubscriptionInstance """ + payload, _, _ = self._create( + description=description, sink_sid=sink_sid, types=types + ) + return SubscriptionInstance(self._version, payload) + + def create_with_http_info( + self, description: str, sink_sid: str, types: List[object] + ) -> ApiResponse: + """ + Create the SubscriptionInstance and return response metadata + + :param description: A human readable description for the Subscription **This value should not contain PII.** + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + :param types: An array of objects containing the subscribed Event Types + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + description=description, sink_sid=sink_sid, types=types + ) + instance = SubscriptionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, description: str, sink_sid: str, types: List[object] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -403,12 +639,49 @@ async def create_async( ) headers = values.of({"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, description: str, sink_sid: str, types: List[object] + ) -> SubscriptionInstance: + """ + Asynchronously create the SubscriptionInstance + + :param description: A human readable description for the Subscription **This value should not contain PII.** + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + :param types: An array of objects containing the subscribed Event Types + + :returns: The created SubscriptionInstance + """ + payload, _, _ = await self._create_async( + description=description, sink_sid=sink_sid, types=types + ) return SubscriptionInstance(self._version, payload) + async def create_with_http_info_async( + self, description: str, sink_sid: str, types: List[object] + ) -> ApiResponse: + """ + Asynchronously create the SubscriptionInstance and return response metadata + + :param description: A human readable description for the Subscription **This value should not contain PII.** + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + :param types: An array of objects containing the subscribed Event Types + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + description=description, sink_sid=sink_sid, types=types + ) + instance = SubscriptionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, sink_sid: Union[str, object] = values.unset, @@ -463,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, @@ -484,6 +813,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sink_sid=sink_sid, @@ -513,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( @@ -522,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, @@ -549,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( @@ -579,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 8547fd486b..7ad59f767b 100644 --- a/twilio/rest/events/v1/subscription/subscribed_event.py +++ b/twilio/rest/events/v1/subscription/subscribed_event.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( "subscription_sid": subscription_sid, "type": type or self.type, } + self._context: Optional[SubscribedEventContext] = None @property @@ -87,6 +89,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SubscribedEventInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SubscribedEventInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SubscribedEventInstance": """ Fetch the SubscribedEventInstance @@ -105,6 +125,24 @@ async def fetch_async(self) -> "SubscribedEventInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscribedEventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscribedEventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, schema_version: Union[int, object] = values.unset ) -> "SubscribedEventInstance": @@ -133,6 +171,34 @@ async def update_async( schema_version=schema_version, ) + def update_with_http_info( + self, schema_version: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Update the SubscribedEventInstance with HTTP info + + :param schema_version: The schema version that the Subscription should use. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + schema_version=schema_version, + ) + + async def update_with_http_info_async( + self, schema_version: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SubscribedEventInstance with HTTP info + + :param schema_version: The schema version that the Subscription should use. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + schema_version=schema_version, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -164,6 +230,20 @@ def __init__(self, version: Version, subscription_sid: str, type: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SubscribedEventInstance @@ -171,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: @@ -183,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: @@ -195,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: """ @@ -215,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, @@ -228,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, @@ -257,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. - :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({}) + + 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, 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, @@ -286,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 @@ -304,6 +534,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SubscribedEventInstance: :param payload: Payload response from the API """ + return SubscribedEventInstance( self._version, payload, subscription_sid=self._solution["subscription_sid"] ) @@ -337,16 +568,14 @@ def __init__(self, version: Version, subscription_sid: str): **self._solution ) - def create( + def _create( self, type: str, schema_version: Union[int, object] = values.unset - ) -> SubscribedEventInstance: + ) -> tuple: """ - Create the SubscribedEventInstance - - :param type: Type of event being subscribed to. - :param schema_version: The schema version that the Subscription should use. + Internal helper for create operation - :returns: The created SubscribedEventInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -357,24 +586,57 @@ def create( ) headers = values.of({"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, type: str, schema_version: Union[int, object] = values.unset + ) -> SubscribedEventInstance: + """ + Create the SubscribedEventInstance + + :param type: Type of event being subscribed to. + :param schema_version: The schema version that the Subscription should use. + + :returns: The created SubscribedEventInstance + """ + payload, _, _ = self._create(type=type, schema_version=schema_version) return SubscribedEventInstance( self._version, payload, subscription_sid=self._solution["subscription_sid"] ) - async def create_async( + def create_with_http_info( self, type: str, schema_version: Union[int, object] = values.unset - ) -> SubscribedEventInstance: + ) -> ApiResponse: """ - Asynchronously create the SubscribedEventInstance + Create the SubscribedEventInstance and return response metadata :param type: Type of event being subscribed to. :param schema_version: The schema version that the Subscription should use. - :returns: The created SubscribedEventInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, schema_version=schema_version + ) + instance = SubscribedEventInstance( + self._version, payload, subscription_sid=self._solution["subscription_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, type: str, schema_version: Union[int, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -385,14 +647,51 @@ async def create_async( ) headers = values.of({"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, 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, @@ -443,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, @@ -462,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -488,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( @@ -496,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, @@ -520,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, @@ -547,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: """ @@ -562,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: """ @@ -574,7 +1055,7 @@ async def get_page_async(self, target_url: str) -> SubscribedEventPage: :returns: Page of SubscribedEventInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SubscribedEventPage(self._version, response, self._solution) + return SubscribedEventPage(self._version, response, solution=self._solution) def get(self, type: str) -> SubscribedEventContext: """ diff --git a/twilio/rest/flex_api/v1/assessments.py b/twilio/rest/flex_api/v1/assessments.py index b24d9113d4..003b309a89 100644 --- a/twilio/rest/flex_api/v1/assessments.py +++ b/twilio/rest/flex_api/v1/assessments.py @@ -13,7 +13,8 @@ """ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values +from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -49,9 +50,9 @@ def __init__( self.account_sid: Optional[str] = payload.get("account_sid") self.assessment_sid: Optional[str] = payload.get("assessment_sid") - self.offset: Optional[float] = deserialize.decimal(payload.get("offset")) + self.offset: Optional[str] = payload.get("offset") self.report: Optional[bool] = payload.get("report") - self.weight: Optional[float] = deserialize.decimal(payload.get("weight")) + self.weight: Optional[str] = payload.get("weight") self.agent_id: Optional[str] = payload.get("agent_id") self.segment_id: Optional[str] = payload.get("segment_id") self.user_name: Optional[str] = payload.get("user_name") @@ -59,12 +60,13 @@ def __init__( self.answer_text: Optional[str] = payload.get("answer_text") self.answer_id: Optional[str] = payload.get("answer_id") self.assessment: Optional[Dict[str, object]] = payload.get("assessment") - self.timestamp: Optional[float] = deserialize.decimal(payload.get("timestamp")) + self.timestamp: Optional[str] = payload.get("timestamp") self.url: Optional[str] = payload.get("url") self._solution = { "assessment_sid": assessment_sid or self.assessment_sid, } + self._context: Optional[AssessmentsContext] = None @property @@ -130,6 +132,54 @@ async def update_async( authorization=authorization, ) + def update_with_http_info( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the AssessmentsInstance with HTTP info + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + + async def update_with_http_info_async( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AssessmentsInstance with HTTP info + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -159,6 +209,43 @@ def __init__(self, version: Version, assessment_sid: str): **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, @@ -176,6 +263,58 @@ def update( :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, @@ -183,18 +322,20 @@ def update( "AnswerId": answer_id, } ) - headers = values.of( - { - "Authorization": authorization, - } - ) + 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_sid=self._solution["assessment_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( @@ -214,26 +355,43 @@ async def update_async( :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( - { - "Authorization": authorization, - } + 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( + :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: """ @@ -253,6 +411,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AssessmentsInstance: :param payload: Payload response from the API """ + return AssessmentsInstance(self._version, payload) def __repr__(self) -> str: @@ -277,7 +436,7 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Assessments" - def create( + def _create( self, category_sid: str, category_name: str, @@ -290,23 +449,12 @@ def create( answer_id: str, questionnaire_sid: str, authorization: Union[str, object] = values.unset, - ) -> AssessmentsInstance: + ) -> tuple: """ - Create the AssessmentsInstance + Internal helper for create operation - :param category_sid: The SID of the category - :param category_name: The name of the category - :param segment_id: Segment Id of the conversation - :param agent_id: The id of the Agent - :param offset: The offset of the conversation. - :param metric_id: The question SID selected for assessment - :param metric_name: The question name of the assessment - :param answer_text: The answer text selected by user - :param answer_id: The id of the answer selected by user - :param questionnaire_sid: Questionnaire SID of the associated question - :param authorization: The Authorization HTTP request header - - :returns: The created AssessmentsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -330,13 +478,15 @@ def create( } ) - 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_sid: str, category_name: str, @@ -351,7 +501,7 @@ async def create_async( authorization: Union[str, object] = values.unset, ) -> AssessmentsInstance: """ - Asynchronously create the AssessmentsInstance + Create the AssessmentsInstance :param category_sid: The SID of the category :param category_name: The name of the category @@ -367,6 +517,88 @@ async def create_async( :returns: The created AssessmentsInstance """ + payload, _, _ = self._create( + category_sid=category_sid, + category_name=category_name, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + metric_id=metric_id, + metric_name=metric_name, + answer_text=answer_text, + answer_id=answer_id, + questionnaire_sid=questionnaire_sid, + authorization=authorization, + ) + return AssessmentsInstance(self._version, payload) + + def create_with_http_info( + self, + category_sid: str, + category_name: str, + segment_id: str, + agent_id: str, + offset: float, + metric_id: str, + metric_name: str, + answer_text: str, + answer_id: str, + questionnaire_sid: str, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the AssessmentsInstance and return response metadata + + :param category_sid: The SID of the category + :param category_name: The name of the category + :param segment_id: Segment Id of the conversation + :param agent_id: The id of the Agent + :param offset: The offset of the conversation. + :param metric_id: The question SID selected for assessment + :param metric_name: The question name of the assessment + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param questionnaire_sid: Questionnaire SID of the associated question + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + category_sid=category_sid, + category_name=category_name, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + metric_id=metric_id, + metric_name=metric_name, + answer_text=answer_text, + answer_id=answer_id, + questionnaire_sid=questionnaire_sid, + authorization=authorization, + ) + instance = AssessmentsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + category_sid: str, + category_name: str, + segment_id: str, + agent_id: str, + offset: float, + metric_id: str, + metric_name: str, + answer_text: str, + answer_id: str, + questionnaire_sid: str, + authorization: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -389,12 +621,107 @@ async def create_async( } ) - 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, authorization: Union[str, object] = values.unset, @@ -461,6 +788,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssessmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AssessmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -484,6 +875,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -516,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( @@ -526,6 +919,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AssessmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AssessmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -556,7 +1011,18 @@ 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( @@ -589,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. diff --git a/twilio/rest/flex_api/v1/channel.py b/twilio/rest/flex_api/v1/channel.py index bf4feb99e1..0f223bc426 100644 --- a/twilio/rest/flex_api/v1/channel.py +++ b/twilio/rest/flex_api/v1/channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -55,6 +56,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ChannelContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ChannelInstance": """ Fetch the ChannelInstance @@ -108,6 +128,24 @@ async def fetch_async(self) -> "ChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -135,6 +173,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Channels/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ChannelInstance @@ -142,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: @@ -154,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: @@ -166,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: """ @@ -185,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: """ @@ -215,6 +349,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: :param payload: Payload response from the API """ + return ChannelInstance(self._version, payload) def __repr__(self) -> str: @@ -239,7 +374,7 @@ def __init__(self, version: Version): self._uri = "/Channels" - def create( + def _create( self, flex_flow_sid: str, identity: str, @@ -251,22 +386,12 @@ def create( task_sid: Union[str, object] = values.unset, task_attributes: Union[str, object] = values.unset, long_lived: Union[bool, object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Create the ChannelInstance + Internal helper for create operation - :param flex_flow_sid: The SID of the Flex Flow. - :param identity: The `identity` value that uniquely identifies the new resource's chat User. - :param chat_user_friendly_name: The chat participant's friendly name. - :param chat_friendly_name: The chat channel's friendly name. - :param target: The Target Contact Identity, for example the phone number of an SMS. - :param chat_unique_name: The chat channel's unique name. - :param pre_engagement_data: The pre-engagement data. - :param task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` - :param task_attributes: The Task attributes to be added for the TaskRouter Task. - :param long_lived: Whether to create the channel as long-lived. - - :returns: The created ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -285,13 +410,15 @@ def create( ) headers = values.of({"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 ChannelInstance(self._version, payload) - - async def create_async( + def create( self, flex_flow_sid: str, identity: str, @@ -305,7 +432,7 @@ async def create_async( long_lived: Union[bool, object] = values.unset, ) -> ChannelInstance: """ - Asynchronously create the ChannelInstance + Create the ChannelInstance :param flex_flow_sid: The SID of the Flex Flow. :param identity: The `identity` value that uniquely identifies the new resource's chat User. @@ -320,6 +447,83 @@ async def create_async( :returns: The created ChannelInstance """ + payload, _, _ = self._create( + flex_flow_sid=flex_flow_sid, + identity=identity, + chat_user_friendly_name=chat_user_friendly_name, + chat_friendly_name=chat_friendly_name, + target=target, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + task_sid=task_sid, + task_attributes=task_attributes, + long_lived=long_lived, + ) + return ChannelInstance(self._version, payload) + + def create_with_http_info( + self, + flex_flow_sid: str, + identity: str, + chat_user_friendly_name: str, + chat_friendly_name: str, + target: Union[str, object] = values.unset, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + task_attributes: Union[str, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ChannelInstance and return response metadata + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The `identity` value that uniquely identifies the new resource's chat User. + :param chat_user_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param target: The Target Contact Identity, for example the phone number of an SMS. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + :param task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` + :param task_attributes: The Task attributes to be added for the TaskRouter Task. + :param long_lived: Whether to create the channel as long-lived. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + flex_flow_sid=flex_flow_sid, + identity=identity, + chat_user_friendly_name=chat_user_friendly_name, + chat_friendly_name=chat_friendly_name, + target=target, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + task_sid=task_sid, + task_attributes=task_attributes, + long_lived=long_lived, + ) + instance = ChannelInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + flex_flow_sid: str, + identity: str, + chat_user_friendly_name: str, + chat_friendly_name: str, + target: Union[str, object] = values.unset, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + task_attributes: Union[str, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -337,12 +541,101 @@ async def create_async( ) headers = values.of({"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, + flex_flow_sid: str, + identity: str, + chat_user_friendly_name: str, + chat_friendly_name: str, + target: Union[str, object] = values.unset, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + task_attributes: Union[str, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The `identity` value that uniquely identifies the new resource's chat User. + :param chat_user_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param target: The Target Contact Identity, for example the phone number of an SMS. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + :param task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` + :param task_attributes: The Task attributes to be added for the TaskRouter Task. + :param long_lived: Whether to create the channel as long-lived. + + :returns: The created ChannelInstance + """ + payload, _, _ = await self._create_async( + flex_flow_sid=flex_flow_sid, + identity=identity, + chat_user_friendly_name=chat_user_friendly_name, + chat_friendly_name=chat_friendly_name, + target=target, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + task_sid=task_sid, + task_attributes=task_attributes, + long_lived=long_lived, + ) return ChannelInstance(self._version, payload) + async def create_with_http_info_async( + self, + flex_flow_sid: str, + identity: str, + chat_user_friendly_name: str, + chat_friendly_name: str, + target: Union[str, object] = values.unset, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + task_attributes: Union[str, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ChannelInstance and return response metadata + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The `identity` value that uniquely identifies the new resource's chat User. + :param chat_user_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param target: The Target Contact Identity, for example the phone number of an SMS. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + :param task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` + :param task_attributes: The Task attributes to be added for the TaskRouter Task. + :param long_lived: Whether to create the channel as long-lived. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + flex_flow_sid=flex_flow_sid, + identity=identity, + chat_user_friendly_name=chat_user_friendly_name, + chat_friendly_name=chat_friendly_name, + target=target, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + task_sid=task_sid, + task_attributes=task_attributes, + long_lived=long_lived, + ) + instance = ChannelInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -393,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, @@ -412,6 +755,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -438,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( @@ -446,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, @@ -470,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( @@ -497,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 bec7034cfe..6e8f586a01 100644 --- a/twilio/rest/flex_api/v1/configuration.py +++ b/twilio/rest/flex_api/v1/configuration.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -237,6 +238,34 @@ async def fetch_async( ui_version=ui_version, ) + def fetch_with_http_info( + self, ui_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ConfigurationInstance with HTTP info + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + ui_version=ui_version, + ) + + async def fetch_with_http_info_async( + self, ui_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance with HTTP info + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + ui_version=ui_version, + ) + def update( self, body: Union[object, object] = values.unset ) -> "ConfigurationInstance": @@ -265,6 +294,34 @@ async def update_async( body=body, ) + def update_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Update the ConfigurationInstance with HTTP info + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + body=body, + ) + + async def update_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConfigurationInstance with HTTP info + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + body=body, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -287,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: @@ -297,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 + + :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) + """ - data = values.of( + 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( @@ -321,21 +433,47 @@ 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 @@ -347,19 +485,42 @@ def update( :returns: The updated ConfigurationInstance """ - data = values.of({}) - headers = values.of( - { - "body": body, - } - ) + 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({}) - payload = self._version.update( + 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 ) - return ConfigurationInstance(self._version, payload) - async def update_async( self, body: Union[object, object] = values.unset ) -> ConfigurationInstance: @@ -370,18 +531,22 @@ async def update_async( :returns: The updated ConfigurationInstance """ - data = values.of({}) - headers = values.of( - { - "body": body, - } - ) + payload, _, _ = await self._update_async(body=body) + return ConfigurationInstance(self._version, payload) - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return ConfigurationInstance(self._version, payload) + :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: """ diff --git a/twilio/rest/flex_api/v1/flex_flow.py b/twilio/rest/flex_api/v1/flex_flow.py index 531dd470b2..35f61b0683 100644 --- a/twilio/rest/flex_api/v1/flex_flow.py +++ b/twilio/rest/flex_api/v1/flex_flow.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -85,6 +86,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[FlexFlowContext] = None @property @@ -120,6 +122,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FlexFlowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlexFlowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "FlexFlowInstance": """ Fetch the FlexFlowInstance @@ -138,6 +158,24 @@ async def fetch_async(self) -> "FlexFlowInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlexFlowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlexFlowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -268,6 +306,136 @@ async def update_async( integration_retry_count=integration_retry_count, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the FlexFlowInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FlexFlowInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -295,6 +463,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/FlexFlows/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the FlexFlowInstance @@ -302,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: @@ -314,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: @@ -326,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: """ @@ -345,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, @@ -378,30 +642,14 @@ 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, @@ -425,16 +673,17 @@ def update( "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, @@ -457,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. @@ -479,38 +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": 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, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 @@ -529,6 +1029,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FlexFlowInstance: :param payload: Payload response from the API """ + return FlexFlowInstance(self._version, payload) def __repr__(self) -> str: @@ -546,14 +1047,271 @@ def __init__(self, version: Version): """ Initialize the FlexFlowList - :param version: Version that contains the resource + :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: + 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" - """ - 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, @@ -576,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. @@ -598,39 +1356,28 @@ def create( :returns: The created FlexFlowInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "ChatServiceSid": chat_service_sid, - "ChannelType": channel_type, - "ContactIdentity": contact_identity, - "Enabled": serialize.boolean_to_string(enabled), - "IntegrationType": integration_type, - "Integration.FlowSid": integration_flow_sid, - "Integration.Url": integration_url, - "Integration.WorkspaceSid": integration_workspace_sid, - "Integration.WorkflowSid": integration_workflow_sid, - "Integration.Channel": integration_channel, - "Integration.Timeout": integration_timeout, - "Integration.Priority": integration_priority, - "Integration.CreationOnMessage": serialize.boolean_to_string( - integration_creation_on_message - ), - "LongLived": serialize.boolean_to_string(long_lived), - "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), - "Integration.RetryCount": integration_retry_count, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, ) - return FlexFlowInstance(self._version, payload) - async def create_async( + async def create_with_http_info_async( self, friendly_name: str, chat_service_sid: str, @@ -651,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. @@ -673,39 +1420,29 @@ async def create_async( :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. - :returns: The created FlexFlowInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "FriendlyName": friendly_name, - "ChatServiceSid": chat_service_sid, - "ChannelType": channel_type, - "ContactIdentity": contact_identity, - "Enabled": serialize.boolean_to_string(enabled), - "IntegrationType": integration_type, - "Integration.FlowSid": integration_flow_sid, - "Integration.Url": integration_url, - "Integration.WorkspaceSid": integration_workspace_sid, - "Integration.WorkflowSid": integration_workflow_sid, - "Integration.Channel": integration_channel, - "Integration.Timeout": integration_timeout, - "Integration.Priority": integration_priority, - "Integration.CreationOnMessage": serialize.boolean_to_string( - integration_creation_on_message - ), - "LongLived": serialize.boolean_to_string(long_lived), - "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), - "Integration.RetryCount": integration_retry_count, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, ) - - return FlexFlowInstance(self._version, payload) + instance = FlexFlowInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -763,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, @@ -784,6 +1577,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -813,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( @@ -822,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, @@ -849,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( @@ -879,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 faeb6ae62c..0f48ce1cc5 100644 --- a/twilio/rest/flex_api/v1/insights_assessments_comment.py +++ b/twilio/rest/flex_api/v1/insights_assessments_comment.py @@ -13,7 +13,8 @@ """ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, values +from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -43,14 +44,14 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.account_sid: Optional[str] = payload.get("account_sid") self.assessment_sid: Optional[str] = payload.get("assessment_sid") self.comment: Optional[Dict[str, object]] = payload.get("comment") - self.offset: Optional[float] = deserialize.decimal(payload.get("offset")) + self.offset: Optional[str] = payload.get("offset") self.report: Optional[bool] = payload.get("report") - self.weight: Optional[float] = deserialize.decimal(payload.get("weight")) + self.weight: Optional[str] = payload.get("weight") self.agent_id: Optional[str] = payload.get("agent_id") self.segment_id: Optional[str] = payload.get("segment_id") self.user_name: Optional[str] = payload.get("user_name") self.user_email: Optional[str] = payload.get("user_email") - self.timestamp: Optional[float] = deserialize.decimal(payload.get("timestamp")) + self.timestamp: Optional[str] = payload.get("timestamp") self.url: Optional[str] = payload.get("url") def __repr__(self) -> str: @@ -73,6 +74,7 @@ def get_instance( :param payload: Payload response from the API """ + return InsightsAssessmentsCommentInstance(self._version, payload) def __repr__(self) -> str: @@ -97,7 +99,7 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Assessments/Comments" - def create( + def _create( self, category_id: str, category_name: str, @@ -106,19 +108,12 @@ def create( agent_id: str, offset: float, authorization: Union[str, object] = values.unset, - ) -> InsightsAssessmentsCommentInstance: + ) -> tuple: """ - Create the InsightsAssessmentsCommentInstance - - :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 + Internal helper for create operation - :returns: The created InsightsAssessmentsCommentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -138,13 +133,15 @@ def create( } ) - 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, @@ -155,7 +152,7 @@ async def create_async( authorization: Union[str, object] = values.unset, ) -> InsightsAssessmentsCommentInstance: """ - Asynchronously create the InsightsAssessmentsCommentInstance + Create the InsightsAssessmentsCommentInstance :param category_id: The ID of the category :param category_name: The name of the category @@ -167,6 +164,68 @@ async def create_async( :returns: The created InsightsAssessmentsCommentInstance """ + payload, _, _ = self._create( + category_id=category_id, + category_name=category_name, + comment=comment, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + authorization=authorization, + ) + return InsightsAssessmentsCommentInstance(self._version, payload) + + def create_with_http_info( + self, + category_id: str, + category_name: str, + comment: str, + segment_id: str, + agent_id: str, + offset: float, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the InsightsAssessmentsCommentInstance and return response metadata + + :param category_id: The ID of the category + :param category_name: The name of the category + :param comment: The Assessment comment. + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param offset: The offset + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + category_id=category_id, + category_name=category_name, + comment=comment, + segment_id=segment_id, + agent_id=agent_id, + offset=offset, + authorization=authorization, + ) + instance = InsightsAssessmentsCommentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + category_id: str, + category_name: str, + comment: str, + segment_id: str, + agent_id: str, + offset: float, + authorization: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -185,12 +244,83 @@ async def create_async( } ) - 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, authorization: Union[str, object] = values.unset, @@ -263,6 +393,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsAssessmentsCommentInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsAssessmentsCommentInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -288,6 +488,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -323,6 +524,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -334,6 +536,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsAssessmentsCommentInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsAssessmentsCommentInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -367,7 +637,18 @@ 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( @@ -403,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 d08608c7e4..c407089755 100644 --- a/twilio/rest/flex_api/v1/insights_conversations.py +++ b/twilio/rest/flex_api/v1/insights_conversations.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InsightsConversationsInstance :param payload: Payload response from the API """ + return InsightsConversationsInstance(self._version, payload) def __repr__(self) -> str: @@ -147,6 +149,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsConversationsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsConversationsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -170,6 +236,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -202,6 +269,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -212,6 +280,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsConversationsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsConversationsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -242,7 +372,18 @@ 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( @@ -275,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 1724e2a253..3ecf2f8156 100644 --- a/twilio/rest/flex_api/v1/insights_questionnaires.py +++ b/twilio/rest/flex_api/v1/insights_questionnaires.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( self._solution = { "questionnaire_sid": questionnaire_sid or self.questionnaire_sid, } + self._context: Optional[InsightsQuestionnairesContext] = None @property @@ -94,6 +96,34 @@ async def delete_async( authorization=authorization, ) + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + authorization=authorization, + ) + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + authorization=authorization, + ) + def fetch( self, authorization: Union[str, object] = values.unset ) -> "InsightsQuestionnairesInstance": @@ -122,6 +152,34 @@ async def fetch_async( authorization=authorization, ) + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsQuestionnairesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + authorization=authorization, + ) + + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InsightsQuestionnairesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + authorization=authorization, + ) + def update( self, active: bool, @@ -176,6 +234,60 @@ async def update_async( question_sids=question_sids, ) + def update_with_http_info( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Update the InsightsQuestionnairesInstance with HTTP info + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + + async def update_with_http_info_async( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesInstance with HTTP info + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -207,6 +319,25 @@ def __init__(self, version: Version, questionnaire_sid: str): ) ) + def _delete(self, authorization: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self, authorization: Union[str, object] = values.unset) -> bool: """ Deletes the InsightsQuestionnairesInstance @@ -215,13 +346,42 @@ def delete(self, authorization: Union[str, object] = values.unset) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(authorization=authorization) + return success + + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(authorization=authorization) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "Authorization": authorization, } ) - 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, authorization: Union[str, object] = values.unset @@ -233,14 +393,44 @@ async def delete_async( :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "Authorization": authorization, - } + success, _, _ = await self._delete_async(authorization=authorization) + return success + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async( + authorization=authorization ) + return ApiResponse(data=success, status_code=status_code, headers=headers) - return await self._version.delete_async( - method="DELETE", uri=self._uri, 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( @@ -253,20 +443,54 @@ def fetch( :returns: The fetched InsightsQuestionnairesInstance """ - - data = values.of( - { - "Authorization": authorization, - } + payload, _, _ = self._fetch(authorization=authorization) + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], ) - 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, questionnaire_sid=self._solution["questionnaire_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async( self, authorization: Union[str, object] = values.unset @@ -278,42 +502,48 @@ async def fetch_async( :returns: The fetched InsightsQuestionnairesInstance """ - - data = values.of( - { - "Authorization": authorization, - } + payload, _, _ = await self._fetch_async(authorization=authorization) + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], ) - 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 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 = 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( + def _update( self, active: bool, authorization: Union[str, object] = values.unset, name: Union[str, object] = values.unset, description: Union[str, object] = values.unset, question_sids: Union[List[str], object] = values.unset, - ) -> InsightsQuestionnairesInstance: + ) -> tuple: """ - Update the InsightsQuestionnairesInstance - - :param active: The flag to enable or disable questionnaire - :param authorization: The Authorization HTTP request header - :param name: The name of this questionnaire - :param description: The description of this questionnaire - :param question_sids: The list of questions sids under a questionnaire + Internal helper for update operation - :returns: The updated InsightsQuestionnairesInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Active": serialize.boolean_to_string(active), @@ -322,32 +552,64 @@ def update( "QuestionSids": serialize.map(question_sids, lambda e: e), } ) - headers = values.of( - { - "Authorization": authorization, - } - ) + 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" - 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, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> InsightsQuestionnairesInstance: + """ + Update the InsightsQuestionnairesInstance + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The updated InsightsQuestionnairesInstance + """ + payload, _, _ = self._update( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) return InsightsQuestionnairesInstance( self._version, payload, questionnaire_sid=self._solution["questionnaire_sid"], ) - async def update_async( + def update_with_http_info( self, active: bool, authorization: Union[str, object] = values.unset, name: Union[str, object] = values.unset, description: Union[str, object] = values.unset, question_sids: Union[List[str], object] = values.unset, - ) -> InsightsQuestionnairesInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the InsightsQuestionnairesInstance + Update the InsightsQuestionnairesInstance and return response metadata :param active: The flag to enable or disable questionnaire :param authorization: The Authorization HTTP request header @@ -355,8 +617,37 @@ async def update_async( :param description: The description of this questionnaire :param question_sids: The list of questions sids under a questionnaire - :returns: The updated InsightsQuestionnairesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + instance = InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> tuple: """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "Active": serialize.boolean_to_string(active), @@ -365,28 +656,93 @@ async def update_async( "QuestionSids": serialize.map(question_sids, lambda e: e), } ) - headers = values.of( - { - "Authorization": authorization, - } - ) + headers = values.of({}) - payload = await self._version.update_async( - 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, - questionnaire_sid=self._solution["questionnaire_sid"], - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - def __repr__(self) -> str: - """ - Provide a friendly representation + headers["Accept"] = "application/json" - :returns: Machine friendly representation - """ + 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, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> InsightsQuestionnairesInstance: + """ + Asynchronous coroutine to update the InsightsQuestionnairesInstance + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The updated InsightsQuestionnairesInstance + """ + payload, _, _ = await self._update_async( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + async def update_with_http_info_async( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesInstance and return response metadata + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + instance = InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) return "".format(context) @@ -399,6 +755,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InsightsQuestionnairesInstanc :param payload: Payload response from the API """ + return InsightsQuestionnairesInstance(self._version, payload) def __repr__(self) -> str: @@ -423,24 +780,19 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Questionnaires" - def create( + def _create( self, name: str, authorization: Union[str, object] = values.unset, description: Union[str, object] = values.unset, active: Union[bool, object] = values.unset, question_sids: Union[List[str], object] = values.unset, - ) -> InsightsQuestionnairesInstance: + ) -> tuple: """ - Create the InsightsQuestionnairesInstance + Internal helper for create operation - :param name: The name of this questionnaire - :param authorization: The Authorization HTTP request header - :param description: The description of this questionnaire - :param active: The flag to enable or disable questionnaire - :param question_sids: The list of questions sids under a questionnaire - - :returns: The created InsightsQuestionnairesInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -458,13 +810,15 @@ def create( } ) - 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, authorization: Union[str, object] = values.unset, @@ -473,7 +827,7 @@ async def create_async( question_sids: Union[List[str], object] = values.unset, ) -> InsightsQuestionnairesInstance: """ - Asynchronously create the InsightsQuestionnairesInstance + Create the InsightsQuestionnairesInstance :param name: The name of this questionnaire :param authorization: The Authorization HTTP request header @@ -483,6 +837,58 @@ async def create_async( :returns: The created InsightsQuestionnairesInstance """ + payload, _, _ = self._create( + name=name, + authorization=authorization, + description=description, + active=active, + question_sids=question_sids, + ) + return InsightsQuestionnairesInstance(self._version, payload) + + def create_with_http_info( + self, + name: str, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + active: Union[bool, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Create the InsightsQuestionnairesInstance and return response metadata + + :param name: The name of this questionnaire + :param authorization: The Authorization HTTP request header + :param description: The description of this questionnaire + :param active: The flag to enable or disable questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + name=name, + authorization=authorization, + description=description, + active=active, + question_sids=question_sids, + ) + instance = InsightsQuestionnairesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + name: str, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + active: Union[bool, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -499,12 +905,71 @@ async def create_async( } ) - 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, authorization: Union[str, object] = values.unset, @@ -571,6 +1036,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsQuestionnairesInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + include_inactive=include_inactive, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsQuestionnairesInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + include_inactive=include_inactive, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -594,6 +1123,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -626,6 +1156,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -636,6 +1167,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsQuestionnairesInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + include_inactive=include_inactive, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsQuestionnairesInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + include_inactive=include_inactive, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -666,7 +1259,18 @@ 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 InsightsQuestionnairesPage(self._version, response) async def page_async( @@ -699,11 +1303,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 InsightsQuestionnairesPage(self._version, response) + def page_with_http_info( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param include_inactive: Flag indicating whether to include inactive questionnaires or not + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsQuestionnairesPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "IncludeInactive": serialize.boolean_to_string(include_inactive), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsQuestionnairesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param include_inactive: Flag indicating whether to include inactive questionnaires or not + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsQuestionnairesPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "IncludeInactive": serialize.boolean_to_string(include_inactive), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsQuestionnairesPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> InsightsQuestionnairesPage: """ Retrieve a specific page of InsightsQuestionnairesInstance records from the API. diff --git a/twilio/rest/flex_api/v1/insights_questionnaires_category.py b/twilio/rest/flex_api/v1/insights_questionnaires_category.py index aba8eb8bdd..9cc42e866a 100644 --- a/twilio/rest/flex_api/v1/insights_questionnaires_category.py +++ b/twilio/rest/flex_api/v1/insights_questionnaires_category.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -45,6 +46,7 @@ def __init__( self._solution = { "category_sid": category_sid or self.category_sid, } + self._context: Optional[InsightsQuestionnairesCategoryContext] = None @property @@ -88,6 +90,34 @@ async def delete_async( authorization=authorization, ) + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesCategoryInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + authorization=authorization, + ) + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesCategoryInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + authorization=authorization, + ) + def update( self, name: str, authorization: Union[str, object] = values.unset ) -> "InsightsQuestionnairesCategoryInstance": @@ -120,6 +150,38 @@ async def update_async( authorization=authorization, ) + def update_with_http_info( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the InsightsQuestionnairesCategoryInstance with HTTP info + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + name=name, + authorization=authorization, + ) + + async def update_with_http_info_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesCategoryInstance with HTTP info + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + name=name, + authorization=authorization, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -151,6 +213,25 @@ def __init__(self, version: Version, category_sid: str): **self._solution ) + def _delete(self, authorization: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self, authorization: Union[str, object] = values.unset) -> bool: """ Deletes the InsightsQuestionnairesCategoryInstance @@ -159,13 +240,42 @@ def delete(self, authorization: Union[str, object] = values.unset) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(authorization=authorization) + return success + + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesCategoryInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(authorization=authorization) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "Authorization": authorization, } ) - 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, authorization: Union[str, object] = values.unset @@ -177,14 +287,53 @@ async def delete_async( :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( { - "Authorization": authorization, + "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( @@ -198,23 +347,59 @@ def update( :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( - { - "Authorization": authorization, - } - ) + 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_sid=self._solution["category_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( @@ -228,24 +413,29 @@ async def update_async( :returns: The updated InsightsQuestionnairesCategoryInstance """ - data = values.of( - { - "Name": name, - } - ) - headers = values.of( - { - "Authorization": authorization, - } + 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( + :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: """ @@ -269,6 +459,7 @@ def get_instance( :param payload: Payload response from the API """ + return InsightsQuestionnairesCategoryInstance(self._version, payload) def __repr__(self) -> str: @@ -293,16 +484,14 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Categories" - def create( + def _create( self, name: str, authorization: Union[str, object] = values.unset - ) -> InsightsQuestionnairesCategoryInstance: + ) -> tuple: """ - Create the InsightsQuestionnairesCategoryInstance + Internal helper for create operation - :param name: The name of this category. - :param authorization: The Authorization HTTP request header - - :returns: The created InsightsQuestionnairesCategoryInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -317,23 +506,54 @@ def create( } ) - 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( + def create( self, name: str, authorization: Union[str, object] = values.unset ) -> InsightsQuestionnairesCategoryInstance: """ - Asynchronously create the InsightsQuestionnairesCategoryInstance + Create the InsightsQuestionnairesCategoryInstance :param name: The name of this category. :param authorization: The Authorization HTTP request header :returns: The created InsightsQuestionnairesCategoryInstance """ + payload, _, _ = self._create(name=name, authorization=authorization) + return InsightsQuestionnairesCategoryInstance(self._version, payload) + + def create_with_http_info( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the InsightsQuestionnairesCategoryInstance and return response metadata + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + name=name, authorization=authorization + ) + instance = InsightsQuestionnairesCategoryInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -347,12 +567,45 @@ async def create_async( } ) - 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, authorization: Union[str, object] = values.unset, @@ -409,6 +662,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsQuestionnairesCategoryInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsQuestionnairesCategoryInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -430,6 +739,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -459,6 +769,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -468,6 +779,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsQuestionnairesCategoryInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsQuestionnairesCategoryInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -495,7 +862,18 @@ 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 InsightsQuestionnairesCategoryPage(self._version, response) async def page_async( @@ -525,11 +903,106 @@ 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 InsightsQuestionnairesCategoryPage(self._version, response) + def page_with_http_info( + self, + authorization: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsQuestionnairesCategoryPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsQuestionnairesCategoryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsQuestionnairesCategoryPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsQuestionnairesCategoryPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> InsightsQuestionnairesCategoryPage: """ Retrieve a specific page of InsightsQuestionnairesCategoryInstance records from the API. diff --git a/twilio/rest/flex_api/v1/insights_questionnaires_question.py b/twilio/rest/flex_api/v1/insights_questionnaires_question.py index 363d5c07b1..e8a88190b6 100644 --- a/twilio/rest/flex_api/v1/insights_questionnaires_question.py +++ b/twilio/rest/flex_api/v1/insights_questionnaires_question.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( self._solution = { "question_sid": question_sid or self.question_sid, } + self._context: Optional[InsightsQuestionnairesQuestionContext] = None @property @@ -100,6 +102,34 @@ async def delete_async( authorization=authorization, ) + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesQuestionInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + authorization=authorization, + ) + + async def delete_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesQuestionInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + authorization=authorization, + ) + def update( self, allow_na: bool, @@ -160,6 +190,66 @@ async def update_async( answer_set_id=answer_set_id, ) + def update_with_http_info( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the InsightsQuestionnairesQuestionInstance with HTTP info + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + + async def update_with_http_info_async( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InsightsQuestionnairesQuestionInstance with HTTP info + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -191,6 +281,25 @@ def __init__(self, version: Version, question_sid: str): **self._solution ) + def _delete(self, authorization: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self, authorization: Union[str, object] = values.unset) -> bool: """ Deletes the InsightsQuestionnairesQuestionInstance @@ -199,13 +308,42 @@ def delete(self, authorization: Union[str, object] = values.unset) -> bool: :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete(authorization=authorization) + return success + + def delete_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the InsightsQuestionnairesQuestionInstance and return response metadata + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete(authorization=authorization) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of( { "Authorization": authorization, } ) - 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, authorization: Union[str, object] = values.unset @@ -217,14 +355,63 @@ async def delete_async( :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( { - "Authorization": authorization, + "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( @@ -248,6 +435,68 @@ def update( :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": serialize.boolean_to_string(allow_na), @@ -257,18 +506,20 @@ def update( "AnswerSetId": answer_set_id, } ) - headers = values.of( - { - "Authorization": authorization, - } - ) + 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_sid=self._solution["question_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( @@ -292,28 +543,51 @@ async def update_async( :returns: The updated InsightsQuestionnairesQuestionInstance """ - data = values.of( - { - "AllowNa": serialize.boolean_to_string(allow_na), - "CategorySid": category_sid, - "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( - { - "Authorization": authorization, - } + 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( + :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: """ @@ -337,6 +611,7 @@ def get_instance( :param payload: Payload response from the API """ + return InsightsQuestionnairesQuestionInstance(self._version, payload) def __repr__(self) -> str: @@ -361,7 +636,7 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Questions" - def create( + def _create( self, category_sid: str, question: str, @@ -369,18 +644,12 @@ def create( allow_na: bool, authorization: Union[str, object] = values.unset, description: Union[str, object] = values.unset, - ) -> InsightsQuestionnairesQuestionInstance: + ) -> tuple: """ - Create the InsightsQuestionnairesQuestionInstance - - :param category_sid: The SID of the category - :param question: The question. - :param answer_set_id: The answer_set for the question. - :param allow_na: The flag to enable for disable NA for answer. - :param authorization: The Authorization HTTP request header - :param description: The description for the question. + Internal helper for create operation - :returns: The created InsightsQuestionnairesQuestionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -399,13 +668,15 @@ def create( } ) - 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_sid: str, question: str, @@ -415,7 +686,7 @@ async def create_async( description: Union[str, object] = values.unset, ) -> InsightsQuestionnairesQuestionInstance: """ - Asynchronously create the InsightsQuestionnairesQuestionInstance + Create the InsightsQuestionnairesQuestionInstance :param category_sid: The SID of the category :param question: The question. @@ -426,6 +697,63 @@ async def create_async( :returns: The created InsightsQuestionnairesQuestionInstance """ + payload, _, _ = self._create( + category_sid=category_sid, + question=question, + answer_set_id=answer_set_id, + allow_na=allow_na, + authorization=authorization, + description=description, + ) + return InsightsQuestionnairesQuestionInstance(self._version, payload) + + 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( { @@ -443,12 +771,77 @@ async def create_async( } ) - 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, authorization: Union[str, object] = values.unset, @@ -515,6 +908,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsQuestionnairesQuestionInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + category_sid=category_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsQuestionnairesQuestionInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + category_sid=category_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -538,6 +995,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -570,6 +1028,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -580,6 +1039,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsQuestionnairesQuestionInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + category_sid=category_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsQuestionnairesQuestionInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + category_sid=category_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -610,7 +1131,18 @@ 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 InsightsQuestionnairesQuestionPage(self._version, response) async def page_async( @@ -643,11 +1175,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 InsightsQuestionnairesQuestionPage(self._version, response) + def page_with_http_info( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param category_sid: The list of category SIDs + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsQuestionnairesQuestionPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "CategorySid": serialize.map(category_sid, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InsightsQuestionnairesQuestionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param authorization: The Authorization HTTP request header + :param category_sid: The list of category SIDs + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InsightsQuestionnairesQuestionPage, status code, and headers + """ + data = values.of( + { + "Authorization": authorization, + "CategorySid": serialize.map(category_sid, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InsightsQuestionnairesQuestionPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> InsightsQuestionnairesQuestionPage: """ Retrieve a specific page of InsightsQuestionnairesQuestionInstance records from the API. diff --git a/twilio/rest/flex_api/v1/insights_segments.py b/twilio/rest/flex_api/v1/insights_segments.py index 2d509802a9..e5232a323a 100644 --- a/twilio/rest/flex_api/v1/insights_segments.py +++ b/twilio/rest/flex_api/v1/insights_segments.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -101,6 +102,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InsightsSegmentsInstance: :param payload: Payload response from the API """ + return InsightsSegmentsInstance(self._version, payload) def __repr__(self) -> str: @@ -197,6 +199,76 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InsightsSegmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InsightsSegmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, authorization: Union[str, object] = values.unset, @@ -222,6 +294,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( authorization=authorization, @@ -257,6 +330,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -268,6 +342,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InsightsSegmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InsightsSegmentsInstance and returns headers from first page + + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, authorization: Union[str, object] = values.unset, @@ -301,7 +443,18 @@ 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( @@ -337,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. diff --git a/twilio/rest/flex_api/v1/insights_session.py b/twilio/rest/flex_api/v1/insights_session.py index b4174aa949..d633933625 100644 --- a/twilio/rest/flex_api/v1/insights_session.py +++ b/twilio/rest/flex_api/v1/insights_session.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -82,6 +83,34 @@ async def create_async( authorization=authorization, ) + def create_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the InsightsSessionInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + authorization=authorization, + ) + + async def create_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the InsightsSessionInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + authorization=authorization, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -104,6 +133,29 @@ def __init__(self, version: Version): self._uri = "/Insights/Session" + def _create(self, authorization: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, authorization: Union[str, object] = values.unset ) -> InsightsSessionInstance: @@ -114,15 +166,47 @@ def create( :returns: The created InsightsSessionInstance """ - data = values.of( - { - "Authorization": authorization, - } - ) + payload, _, _ = self._create(authorization=authorization) + return InsightsSessionInstance(self._version, payload) - payload = self._version.create(method="POST", uri=self._uri, data=data) + def create_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the InsightsSessionInstance and return response metadata - return InsightsSessionInstance(self._version, payload) + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(authorization=authorization) + instance = InsightsSessionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) async def create_async( self, authorization: Union[str, object] = values.unset @@ -134,17 +218,24 @@ async def create_async( :returns: The created InsightsSessionInstance """ - data = values.of( - { - "Authorization": authorization, - } - ) + payload, _, _ = await self._create_async(authorization=authorization) + return InsightsSessionInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data - ) + async def create_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the InsightsSessionInstance and return response metadata - return InsightsSessionInstance(self._version, payload) + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + authorization=authorization + ) + instance = InsightsSessionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ diff --git a/twilio/rest/flex_api/v1/insights_settings_answer_sets.py b/twilio/rest/flex_api/v1/insights_settings_answer_sets.py index d426e215a9..8f6938ded8 100644 --- a/twilio/rest/flex_api/v1/insights_settings_answer_sets.py +++ b/twilio/rest/flex_api/v1/insights_settings_answer_sets.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -63,14 +64,12 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Settings/AnswerSets" - def fetch( - self, authorization: Union[str, object] = values.unset - ) -> InsightsSettingsAnswerSetsInstance: + def _fetch(self, authorization: Union[str, object] = values.unset) -> tuple: """ - Asynchronously fetch the InsightsSettingsAnswerSetsInstance + Internal helper for fetch operation - :param authorization: The Authorization HTTP request header - :returns: The fetched InsightsSettingsAnswerSetsInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of( { @@ -79,19 +78,46 @@ def fetch( } ) - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + headers["Accept"] = "application/json" - return InsightsSettingsAnswerSetsInstance(self._version, payload) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - async def fetch_async( + def fetch( self, authorization: Union[str, object] = values.unset ) -> InsightsSettingsAnswerSetsInstance: """ - Asynchronously fetch the InsightsSettingsAnswerSetsInstance + Fetch the InsightsSettingsAnswerSetsInstance :param authorization: The Authorization HTTP request header :returns: The fetched InsightsSettingsAnswerSetsInstance """ + payload, _, _ = self._fetch(authorization=authorization) + return InsightsSettingsAnswerSetsInstance(self._version, payload) + + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsSettingsAnswerSetsInstance and return response metadata + + :param authorization: The Authorization HTTP request header + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(authorization=authorization) + instance = InsightsSettingsAnswerSetsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ headers = values.of( { "Authorization": authorization, @@ -99,12 +125,39 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( + headers["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._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 548b279181..44ca4f4d36 100644 --- a/twilio/rest/flex_api/v1/insights_settings_comment.py +++ b/twilio/rest/flex_api/v1/insights_settings_comment.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,14 +58,12 @@ def __init__(self, version: Version): self._uri = "/Insights/QualityManagement/Settings/CommentTags" - def fetch( - self, authorization: Union[str, object] = values.unset - ) -> InsightsSettingsCommentInstance: + def _fetch(self, authorization: Union[str, object] = values.unset) -> tuple: """ - Asynchronously fetch the InsightsSettingsCommentInstance + Internal helper for fetch operation - :param authorization: The Authorization HTTP request header - :returns: The fetched InsightsSettingsCommentInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of( { @@ -73,19 +72,46 @@ def fetch( } ) - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + headers["Accept"] = "application/json" - return InsightsSettingsCommentInstance(self._version, payload) + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) - async def fetch_async( + def fetch( self, authorization: Union[str, object] = values.unset ) -> InsightsSettingsCommentInstance: """ - Asynchronously fetch the InsightsSettingsCommentInstance + Fetch the InsightsSettingsCommentInstance :param authorization: The Authorization HTTP request header :returns: The fetched InsightsSettingsCommentInstance """ + payload, _, _ = self._fetch(authorization=authorization) + return InsightsSettingsCommentInstance(self._version, payload) + + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsSettingsCommentInstance and return response metadata + + :param authorization: The Authorization HTTP request header + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(authorization=authorization) + instance = InsightsSettingsCommentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ headers = values.of( { "Authorization": authorization, @@ -93,12 +119,39 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( + headers["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._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 9dbea5fa3b..33ef7c663a 100644 --- a/twilio/rest/flex_api/v1/insights_user_roles.py +++ b/twilio/rest/flex_api/v1/insights_user_roles.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,34 @@ async def fetch_async( authorization=authorization, ) + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsUserRolesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + authorization=authorization, + ) + + async def fetch_with_http_info_async( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InsightsUserRolesInstance with HTTP info + + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + authorization=authorization, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -98,6 +127,28 @@ def __init__(self, version: Version): self._uri = "/Insights/UserRoles" + def _fetch(self, authorization: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch( self, authorization: Union[str, object] = values.unset ) -> InsightsUserRolesInstance: @@ -108,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 - return InsightsUserRolesInstance( + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(authorization=authorization) + instance = InsightsUserRolesInstance( self._version, payload, ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + 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 @@ -132,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: """ diff --git a/twilio/rest/flex_api/v1/interaction/__init__.py b/twilio/rest/flex_api/v1/interaction/__init__.py index 468b3134eb..9e63203161 100644 --- a/twilio/rest/flex_api/v1/interaction/__init__.py +++ b/twilio/rest/flex_api/v1/interaction/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -32,6 +33,7 @@ class InteractionInstance(InstanceResource): :ivar url: :ivar links: :ivar interaction_context_sid: + :ivar webhook_ttid: """ def __init__( @@ -47,10 +49,12 @@ def __init__( self.interaction_context_sid: Optional[str] = payload.get( "interaction_context_sid" ) + self.webhook_ttid: Optional[str] = payload.get("webhook_ttid") self._solution = { "sid": sid or self.sid, } + self._context: Optional[InteractionContext] = None @property @@ -86,6 +90,80 @@ async def fetch_async(self) -> "InteractionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, webhook_ttid: Union[str, object] = values.unset + ) -> "InteractionInstance": + """ + Update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + return self._proxy.update( + webhook_ttid=webhook_ttid, + ) + + async def update_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> "InteractionInstance": + """ + Asynchronous coroutine to update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + return await self._proxy.update_async( + webhook_ttid=webhook_ttid, + ) + + def update_with_http_info( + self, webhook_ttid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the InteractionInstance with HTTP info + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + webhook_ttid=webhook_ttid, + ) + + async def update_with_http_info_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionInstance with HTTP info + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + webhook_ttid=webhook_ttid, + ) + @property def channels(self) -> InteractionChannelList: """ @@ -122,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 @@ -129,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: """ @@ -148,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: @@ -195,20 +433,18 @@ def __init__(self, version: Version): self._uri = "/Interactions" - def create( + def _create( self, channel: object, routing: Union[object, object] = values.unset, interaction_context_sid: Union[str, object] = values.unset, - ) -> InteractionInstance: + webhook_ttid: Union[str, object] = values.unset, + ) -> tuple: """ - Create the InteractionInstance - - :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 + Internal helper for create operation - :returns: The created InteractionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -216,47 +452,153 @@ def create( "Channel": serialize.object(channel), "Routing": serialize.object(routing), "InteractionContextSid": interaction_context_sid, + "WebhookTtid": webhook_ttid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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 InteractionInstance(self._version, payload) - - async def create_async( + def create( self, channel: object, routing: Union[object, object] = values.unset, interaction_context_sid: Union[str, object] = values.unset, + webhook_ttid: Union[str, object] = values.unset, ) -> InteractionInstance: """ - Asynchronously create the InteractionInstance + Create the InteractionInstance :param channel: The Interaction's channel. :param routing: The Interaction's routing logic. :param interaction_context_sid: The Interaction context sid is used for adding a context lookup sid + :param webhook_ttid: The unique identifier for Interaction level webhook :returns: The created InteractionInstance """ + payload, _, _ = self._create( + channel=channel, + routing=routing, + interaction_context_sid=interaction_context_sid, + webhook_ttid=webhook_ttid, + ) + return InteractionInstance(self._version, payload) + + def create_with_http_info( + self, + channel: object, + routing: Union[object, object] = values.unset, + interaction_context_sid: Union[str, object] = values.unset, + webhook_ttid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the InteractionInstance and return response metadata + + :param channel: The Interaction's channel. + :param routing: The Interaction's routing logic. + :param interaction_context_sid: The Interaction context sid is used for adding a context lookup sid + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + channel=channel, + routing=routing, + interaction_context_sid=interaction_context_sid, + webhook_ttid=webhook_ttid, + ) + instance = InteractionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + channel: object, + routing: Union[object, object] = values.unset, + interaction_context_sid: Union[str, object] = values.unset, + webhook_ttid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { "Channel": serialize.object(channel), "Routing": serialize.object(routing), "InteractionContextSid": interaction_context_sid, + "WebhookTtid": webhook_ttid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, + 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 a26dc0425e..2c362c9dbd 100644 --- a/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,6 +26,9 @@ from twilio.rest.flex_api.v1.interaction.interaction_channel.interaction_channel_participant import ( InteractionChannelParticipantList, ) +from twilio.rest.flex_api.v1.interaction.interaction_channel.interaction_transfer import ( + InteractionTransferList, +) class InteractionChannelInstance(InstanceResource): @@ -35,6 +39,8 @@ class ChannelStatus(object): FAILED = "failed" CLOSED = "closed" INACTIVE = "inactive" + PAUSE = "pause" + TRANSFER = "transfer" class Type(object): VOICE = "voice" @@ -85,6 +91,7 @@ def __init__( "interaction_sid": interaction_sid, "sid": sid or self.sid, } + self._context: Optional[InteractionChannelContext] = None @property @@ -121,6 +128,24 @@ async def fetch_async(self) -> "InteractionChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: "InteractionChannelInstance.UpdateChannelStatus", @@ -157,6 +182,42 @@ async def update_async( routing=routing, ) + def update_with_http_info( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the InteractionChannelInstance with HTTP info + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + routing=routing, + ) + + async def update_with_http_info_async( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionChannelInstance with HTTP info + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + routing=routing, + ) + @property def invites(self) -> InteractionChannelInviteList: """ @@ -171,6 +232,13 @@ def participants(self) -> InteractionChannelParticipantList: """ return self._proxy.participants + @property + def transfers(self) -> InteractionTransferList: + """ + Access the transfers + """ + return self._proxy.transfers + def __repr__(self) -> str: """ Provide a friendly representation @@ -204,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: """ @@ -212,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: """ @@ -232,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.UpdateChannelStatus", routing: Union[object, object] = values.unset, - ) -> InteractionChannelInstance: + ) -> tuple: """ - Update the InteractionChannelInstance + Internal helper for update operation - :param status: - :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. - - :returns: The updated InteractionChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "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, @@ -278,32 +417,70 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, status: "InteractionChannelInstance.UpdateChannelStatus", routing: Union[object, object] = values.unset, - ) -> InteractionChannelInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the InteractionChannelInstance + Update the InteractionChannelInstance and return response metadata :param status: :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. - :returns: The updated InteractionChannelInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._update(status=status, routing=routing) + instance = InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "Status": status, "Routing": serialize.object(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, + 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, @@ -311,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: """ @@ -337,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 @@ -355,6 +569,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InteractionChannelInstance: :param payload: Payload response from the API """ + return InteractionChannelInstance( self._version, payload, interaction_sid=self._solution["interaction_sid"] ) @@ -436,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, @@ -455,6 +720,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -481,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( @@ -489,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, @@ -513,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, @@ -540,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: """ @@ -555,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: """ @@ -567,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 2ffa14b1df..b34035b6b2 100644 --- a/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InteractionChannelInviteInsta :param payload: Payload response from the API """ + return InteractionChannelInviteInstance( self._version, payload, @@ -108,13 +110,12 @@ def __init__(self, version: Version, interaction_sid: str, channel_sid: str): ) ) - def create(self, routing: object) -> InteractionChannelInviteInstance: + def _create(self, routing: object) -> tuple: """ - Create the InteractionChannelInviteInstance + Internal helper for create operation - :param routing: The Interaction's routing logic. - - :returns: The created InteractionChannelInviteInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -124,10 +125,23 @@ def create(self, routing: object) -> InteractionChannelInviteInstance: ) headers = values.of({"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, 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,13 +149,29 @@ def create(self, routing: object) -> InteractionChannelInviteInstance: channel_sid=self._solution["channel_sid"], ) - async def create_async(self, routing: object) -> InteractionChannelInviteInstance: + def create_with_http_info(self, routing: object) -> ApiResponse: """ - Asynchronously create the InteractionChannelInviteInstance + Create the InteractionChannelInviteInstance and return response metadata :param routing: The Interaction's routing logic. - :returns: The created InteractionChannelInviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(routing=routing) + instance = InteractionChannelInviteInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, routing: object) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -151,10 +181,23 @@ async def create_async(self, routing: object) -> InteractionChannelInviteInstanc ) headers = values.of({"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, 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 ) - return InteractionChannelInvitePage(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 InteractionChannelInvitePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = InteractionChannelInvitePage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with InteractionChannelInvitePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = InteractionChannelInvitePage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> InteractionChannelInvitePage: """ @@ -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 225ca3efaf..9be568cea4 100644 --- a/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -69,6 +70,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InteractionChannelParticipantContext] = None @property @@ -116,6 +118,34 @@ async def update_async( status=status, ) + def update_with_http_info( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> ApiResponse: + """ + Update the InteractionChannelParticipantInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionChannelParticipantInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -153,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, @@ -183,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({}) + + 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: "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, @@ -213,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 @@ -235,6 +331,7 @@ def get_instance( :param payload: Payload response from the API """ + return InteractionChannelParticipantInstance( self._version, payload, @@ -273,20 +370,17 @@ def __init__(self, version: Version, interaction_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, type: "InteractionChannelParticipantInstance.Type", media_properties: object, routing_properties: Union[object, object] = values.unset, - ) -> InteractionChannelParticipantInstance: + ) -> tuple: """ - Create the InteractionChannelParticipantInstance + Internal helper for create operation - :param type: - :param media_properties: JSON representing the Media Properties for the new Participant. - :param routing_properties: Object representing the Routing Properties for the new Participant. - - :returns: The created InteractionChannelParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -298,10 +392,34 @@ def create( ) headers = values.of({"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, + 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, @@ -309,20 +427,45 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, type: "InteractionChannelParticipantInstance.Type", media_properties: object, routing_properties: Union[object, object] = values.unset, - ) -> InteractionChannelParticipantInstance: + ) -> ApiResponse: """ - Asynchronously create the InteractionChannelParticipantInstance + Create the InteractionChannelParticipantInstance and return response metadata :param type: :param media_properties: JSON representing the Media Properties for the new Participant. :param routing_properties: Object representing the Routing Properties for the new Participant. - :returns: The created InteractionChannelParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + media_properties=media_properties, + routing_properties=routing_properties, + ) + instance = InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "InteractionChannelParticipantInstance.Type", + media_properties: object, + routing_properties: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -334,10 +477,34 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -345,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, @@ -395,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, @@ -414,6 +659,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -440,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( @@ -448,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, @@ -472,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( @@ -501,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: """ @@ -519,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( @@ -535,7 +916,7 @@ async def get_page_async( """ response = await self._version.domain.twilio.request_async("GET", target_url) return InteractionChannelParticipantPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) def get(self, sid: str) -> InteractionChannelParticipantContext: diff --git a/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py new file mode 100644 index 0000000000..13f59fadbc --- /dev/null +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py @@ -0,0 +1,633 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InteractionTransferInstance(InstanceResource): + + class TransferStatus(object): + ACTIVE = "active" + FAILED = "failed" + COMPLETED = "completed" + + class TransferType(object): + WARM = "warm" + COLD = "cold" + EXTERNAL = "external" + + """ + :ivar sid: The unique string created by Twilio to identify an Interaction Transfer resource. + :ivar instance_sid: The SID of the Instance associated with the Transfer. + :ivar account_sid: The SID of the Account that created the Transfer. + :ivar interaction_sid: The Interaction Sid for this channel. + :ivar channel_sid: The Channel Sid for this Transfer. + :ivar execution_sid: The Execution SID associated with the Transfer. + :ivar type: + :ivar status: + :ivar _from: The SID of the Participant initiating the Transfer. + :ivar to: The SID of the Participant receiving the Transfer. + :ivar note_sid: The SID of the Note associated with the Transfer. + :ivar summary_sid: The SID of the Summary associated with the Transfer. + :ivar date_created: The date and time when the Transfer was created. + :ivar date_updated: The date and time when the Transfer was last updated. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + interaction_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.instance_sid: Optional[str] = payload.get("instance_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.interaction_sid: Optional[str] = payload.get("interaction_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.type: Optional["InteractionTransferInstance.TransferType"] = payload.get( + "type" + ) + self.status: Optional["InteractionTransferInstance.TransferStatus"] = ( + payload.get("status") + ) + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.note_sid: Optional[str] = payload.get("note_sid") + self.summary_sid: Optional[str] = payload.get("summary_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + + self._context: Optional[InteractionTransferContext] = None + + @property + def _proxy(self) -> "InteractionTransferContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InteractionTransferContext for this InteractionTransferInstance + """ + if self._context is None: + self._context = InteractionTransferContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "InteractionTransferInstance": + """ + Fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InteractionTransferInstance": + """ + Asynchronous coroutine to fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionTransferInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionTransferInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, body: Union[object, object] = values.unset + ) -> "InteractionTransferInstance": + """ + Update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + return self._proxy.update( + body=body, + ) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> "InteractionTransferInstance": + """ + Asynchronous coroutine to update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + return await self._proxy.update_async( + body=body, + ) + + def update_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Update the InteractionTransferInstance with HTTP info + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + body=body, + ) + + async def update_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionTransferInstance with HTTP info + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + body=body, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InteractionTransferContext(InstanceContext): + + def __init__( + self, version: Version, interaction_sid: str, channel_sid: str, sid: str + ): + """ + Initialize the InteractionTransferContext + + :param version: Version that contains the resource + :param interaction_sid: The Interaction Sid for this channel. + :param channel_sid: The Channel Sid for this Transfer. + :param sid: The unique string created by Twilio to identify a Transfer resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = "/Interactions/{interaction_sid}/Channels/{channel_sid}/Transfers/{sid}".format( + **self._solution + ) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> InteractionTransferInstance: + """ + Fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + payload, _, _ = self._fetch() + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionTransferInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> InteractionTransferInstance: + """ + Asynchronous coroutine to fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + payload, _, _ = await self._fetch_async() + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionTransferInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + payload, _, _ = self._update(body=body) + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Update the InteractionTransferInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(body=body) + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Asynchronous coroutine to update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + payload, _, _ = await self._update_async(body=body) + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InteractionTransferInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(body=body) + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class InteractionTransferList(ListResource): + + def __init__(self, version: Version, interaction_sid: str, channel_sid: str): + """ + Initialize the InteractionTransferList + + :param version: Version that contains the resource + :param interaction_sid: The Interaction Sid for the Interaction + :param channel_sid: The Channel Sid for the Channel. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + } + self._uri = ( + "/Interactions/{interaction_sid}/Channels/{channel_sid}/Transfers".format( + **self._solution + ) + ) + + def _create(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Create the InteractionTransferInstance + + :param body: + + :returns: The created InteractionTransferInstance + """ + payload, _, _ = self._create(body=body) + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the InteractionTransferInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body) + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, body: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Asynchronously create the InteractionTransferInstance + + :param body: + + :returns: The created InteractionTransferInstance + """ + payload, _, _ = await self._create_async(body=body) + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the InteractionTransferInstance and return response metadata + + :param body: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(body=body) + instance = InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def get(self, sid: str) -> InteractionTransferContext: + """ + Constructs a InteractionTransferContext + + :param sid: The unique string created by Twilio to identify a Transfer resource. + """ + return InteractionTransferContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InteractionTransferContext: + """ + Constructs a InteractionTransferContext + + :param sid: The unique string created by Twilio to identify a Transfer resource. + """ + return InteractionTransferContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/flex_api/v1/plugin/__init__.py b/twilio/rest/flex_api/v1/plugin/__init__.py index b6baf8f935..5765f3478d 100644 --- a/twilio/rest/flex_api/v1/plugin/__init__.py +++ b/twilio/rest/flex_api/v1/plugin/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PluginContext] = None @property @@ -105,6 +107,34 @@ async def fetch_async( flex_metadata=flex_metadata, ) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + flex_metadata=flex_metadata, + ) + def update( self, flex_metadata: Union[str, object] = values.unset, @@ -147,6 +177,48 @@ async def update_async( description=description, ) + def update_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the PluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + + async def update_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + @property def plugin_versions(self) -> PluginVersionsList: """ @@ -183,6 +255,28 @@ def __init__(self, version: Version, sid: str): self._plugin_versions: Optional[PluginVersionsList] = None + def _fetch(self, flex_metadata: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch(self, flex_metadata: Union[str, object] = values.unset) -> PluginInstance: """ Fetch the PluginInstance @@ -191,20 +285,54 @@ def fetch(self, flex_metadata: Union[str, object] = values.unset) -> PluginInsta :returns: The fetched PluginInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginInstance( + self._version, + payload, + sid=self._solution["sid"], ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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 - return PluginInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(flex_metadata=flex_metadata) + instance = PluginInstance( self._version, payload, sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async( self, flex_metadata: Union[str, object] = values.unset @@ -216,21 +344,66 @@ async def fetch_async( :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( { - "Flex-Metadata": flex_metadata, + "FriendlyName": friendly_name, + "Description": description, } ) + headers = values.of({}) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata - return PluginInstance( - self._version, - payload, - 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 ) def update( @@ -248,24 +421,71 @@ def update( :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( - { - "Flex-Metadata": flex_metadata, - } - ) + 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" - payload = self._version.update( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return PluginInstance(self._version, payload, sid=self._solution["sid"]) - async def update_async( self, flex_metadata: Union[str, object] = values.unset, @@ -281,23 +501,35 @@ async def update_async( :returns: The updated PluginInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Description": description, - } - ) - headers = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = await self._update_async( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, ) + return PluginInstance(self._version, payload, 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, + 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 - return PluginInstance(self._version, payload, sid=self._solution["sid"]) + :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: @@ -329,6 +561,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PluginInstance: :param payload: Payload response from the API """ + return PluginInstance(self._version, payload) def __repr__(self) -> str: @@ -353,22 +586,18 @@ def __init__(self, version: Version): self._uri = "/PluginService/Plugins" - def create( + def _create( self, unique_name: str, flex_metadata: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, description: Union[str, object] = values.unset, - ) -> PluginInstance: + ) -> tuple: """ - Create the PluginInstance - - :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 + Internal helper for create operation - :returns: The created PluginInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -385,13 +614,15 @@ def create( } ) - 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 PluginInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: str, flex_metadata: Union[str, object] = values.unset, @@ -399,7 +630,7 @@ async def create_async( description: Union[str, object] = values.unset, ) -> PluginInstance: """ - Asynchronously create the PluginInstance + Create the PluginInstance :param unique_name: The Flex Plugin's unique name. :param flex_metadata: The Flex-Metadata HTTP request header @@ -408,6 +639,53 @@ async def create_async( :returns: The created PluginInstance """ + payload, _, _ = self._create( + unique_name=unique_name, + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + return PluginInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: str, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the PluginInstance and return response metadata + + :param unique_name: The Flex Plugin's unique name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + instance = PluginInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: str, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -423,12 +701,65 @@ async def create_async( } ) - 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, + 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, @@ -485,6 +816,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, flex_metadata: Union[str, object] = values.unset, @@ -506,6 +893,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( flex_metadata=flex_metadata, @@ -535,6 +923,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -544,6 +933,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, flex_metadata: Union[str, object] = values.unset, @@ -571,7 +1016,18 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -601,11 +1057,106 @@ async def page_async( } ) + 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 + 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. diff --git a/twilio/rest/flex_api/v1/plugin/plugin_versions.py b/twilio/rest/flex_api/v1/plugin/plugin_versions.py index 3da4de3ac7..acd3330caa 100644 --- a/twilio/rest/flex_api/v1/plugin/plugin_versions.py +++ b/twilio/rest/flex_api/v1/plugin/plugin_versions.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -64,6 +65,7 @@ def __init__( "plugin_sid": plugin_sid, "sid": sid or self.sid, } + self._context: Optional[PluginVersionsContext] = None @property @@ -110,6 +112,34 @@ async def fetch_async( flex_metadata=flex_metadata, ) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginVersionsInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginVersionsInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + flex_metadata=flex_metadata, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,6 +171,28 @@ def __init__(self, version: Version, plugin_sid: str, sid: str): **self._solution ) + def _fetch(self, flex_metadata: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch( self, flex_metadata: Union[str, object] = values.unset ) -> PluginVersionsInstance: @@ -151,21 +203,56 @@ def fetch( :returns: The fetched PluginVersionsInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginVersionsInstance and return response metadata - return PluginVersionsInstance( + :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 @@ -177,23 +264,34 @@ async def fetch_async( :returns: The fetched PluginVersionsInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + 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 - return PluginVersionsInstance( + :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: """ @@ -213,6 +311,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PluginVersionsInstance: :param payload: Payload response from the API """ + return PluginVersionsInstance( self._version, payload, plugin_sid=self._solution["plugin_sid"] ) @@ -246,33 +345,26 @@ def __init__(self, version: Version, plugin_sid: str): **self._solution ) - def create( + def _create( self, - version: str, + resource_version: str, plugin_url: str, flex_metadata: Union[str, object] = values.unset, changelog: Union[str, object] = values.unset, private: Union[bool, object] = values.unset, cli_version: Union[str, object] = values.unset, validate_status: Union[str, object] = values.unset, - ) -> PluginVersionsInstance: + ) -> tuple: """ - Create the PluginVersionsInstance + Internal helper for create operation - :param version: The Flex Plugin Version's version. - :param plugin_url: The URL of the Flex Plugin Version bundle - :param flex_metadata: The Flex-Metadata HTTP request header - :param changelog: The changelog of the Flex Plugin Version. - :param private: Whether this Flex Plugin Version requires authorization. - :param cli_version: The version of Flex Plugins CLI used to create this plugin - :param validate_status: The validation status of the plugin, indicating whether it has been validated - - :returns: The created PluginVersionsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( { - "Version": version, + "Version": resource_version, "PluginUrl": plugin_url, "Changelog": changelog, "Private": serialize.boolean_to_string(private), @@ -287,28 +379,64 @@ def create( } ) - 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, + resource_version: str, + plugin_url: str, + flex_metadata: Union[str, object] = values.unset, + changelog: Union[str, object] = values.unset, + private: Union[bool, object] = values.unset, + cli_version: Union[str, object] = values.unset, + validate_status: Union[str, object] = values.unset, + ) -> PluginVersionsInstance: + """ + Create the PluginVersionsInstance + + :param resource_version: The Flex Plugin Version's version. + :param plugin_url: The URL of the Flex Plugin Version bundle + :param flex_metadata: The Flex-Metadata HTTP request header + :param changelog: The changelog of the Flex Plugin Version. + :param private: Whether this Flex Plugin Version requires authorization. + :param cli_version: The version of Flex Plugins CLI used to create this plugin + :param validate_status: The validation status of the plugin, indicating whether it has been validated + + :returns: The created PluginVersionsInstance + """ + payload, _, _ = self._create( + resource_version=resource_version, + plugin_url=plugin_url, + flex_metadata=flex_metadata, + changelog=changelog, + private=private, + cli_version=cli_version, + validate_status=validate_status, + ) return PluginVersionsInstance( self._version, payload, plugin_sid=self._solution["plugin_sid"] ) - async def create_async( + def create_with_http_info( self, - version: str, + resource_version: str, plugin_url: str, flex_metadata: Union[str, object] = values.unset, changelog: Union[str, object] = values.unset, private: Union[bool, object] = values.unset, cli_version: Union[str, object] = values.unset, validate_status: Union[str, object] = values.unset, - ) -> PluginVersionsInstance: + ) -> ApiResponse: """ - Asynchronously create the PluginVersionsInstance + Create the PluginVersionsInstance and return response metadata - :param version: The Flex Plugin Version's version. + :param resource_version: The Flex Plugin Version's version. :param plugin_url: The URL of the Flex Plugin Version bundle :param flex_metadata: The Flex-Metadata HTTP request header :param changelog: The changelog of the Flex Plugin Version. @@ -316,12 +444,42 @@ async def create_async( :param cli_version: The version of Flex Plugins CLI used to create this plugin :param validate_status: The validation status of the plugin, indicating whether it has been validated - :returns: The created PluginVersionsInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + resource_version=resource_version, + plugin_url=plugin_url, + flex_metadata=flex_metadata, + changelog=changelog, + private=private, + cli_version=cli_version, + validate_status=validate_status, + ) + instance = PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + resource_version: str, + plugin_url: str, + flex_metadata: Union[str, object] = values.unset, + changelog: Union[str, object] = values.unset, + private: Union[bool, object] = values.unset, + cli_version: Union[str, object] = values.unset, + validate_status: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( { - "Version": version, + "Version": resource_version, "PluginUrl": plugin_url, "Changelog": changelog, "Private": serialize.boolean_to_string(private), @@ -336,14 +494,87 @@ async def create_async( } ) - 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, + 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, @@ -400,6 +631,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PluginVersionsInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PluginVersionsInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, flex_metadata: Union[str, object] = values.unset, @@ -421,6 +708,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( flex_metadata=flex_metadata, @@ -450,6 +738,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -459,6 +748,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PluginVersionsInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PluginVersionsInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, flex_metadata: Union[str, object] = values.unset, @@ -486,8 +831,19 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return PluginVersionsPage(self._version, response, self._solution) + 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, @@ -516,10 +872,105 @@ async def page_async( } ) + 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 + 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 + ) ) - return PluginVersionsPage(self._version, response, self._solution) + 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: """ @@ -531,7 +982,7 @@ def get_page(self, target_url: str) -> PluginVersionsPage: :returns: Page of PluginVersionsInstance """ response = self._version.domain.twilio.request("GET", target_url) - return PluginVersionsPage(self._version, response, self._solution) + return PluginVersionsPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> PluginVersionsPage: """ @@ -543,7 +994,7 @@ async def get_page_async(self, target_url: str) -> PluginVersionsPage: :returns: Page of PluginVersionsInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return PluginVersionsPage(self._version, response, self._solution) + return PluginVersionsPage(self._version, response, solution=self._solution) def get(self, sid: str) -> PluginVersionsContext: """ diff --git a/twilio/rest/flex_api/v1/plugin_archive.py b/twilio/rest/flex_api/v1/plugin_archive.py index 68f9bce384..7dbb89ffdc 100644 --- a/twilio/rest/flex_api/v1/plugin_archive.py +++ b/twilio/rest/flex_api/v1/plugin_archive.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PluginArchiveContext] = None @property @@ -101,6 +103,34 @@ async def update_async( flex_metadata=flex_metadata, ) + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + flex_metadata=flex_metadata, + ) + + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + flex_metadata=flex_metadata, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -128,6 +158,29 @@ def __init__(self, version: Version, sid: str): } self._uri = "/PluginService/Plugins/{sid}/Archive".format(**self._solution) + def _update(self, flex_metadata: Union[str, object] = values.unset) -> 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: @@ -138,19 +191,50 @@ def update( :returns: The updated PluginArchiveInstance """ - data = values.of({}) - headers = values.of( - { - "Flex-Metadata": flex_metadata, - } + 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" - payload = self._version.update( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return PluginArchiveInstance(self._version, payload, sid=self._solution["sid"]) - async def update_async( self, flex_metadata: Union[str, object] = values.unset ) -> PluginArchiveInstance: @@ -161,18 +245,26 @@ async def update_async( :returns: The updated PluginArchiveInstance """ - data = values.of({}) - headers = values.of( - { - "Flex-Metadata": flex_metadata, - } - ) + payload, _, _ = await self._update_async(flex_metadata=flex_metadata) + return PluginArchiveInstance(self._version, payload, 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, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginArchiveInstance and return response metadata - return PluginArchiveInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ diff --git a/twilio/rest/flex_api/v1/plugin_configuration/__init__.py b/twilio/rest/flex_api/v1/plugin_configuration/__init__.py index 9b76695243..d98e1f3615 100644 --- a/twilio/rest/flex_api/v1/plugin_configuration/__init__.py +++ b/twilio/rest/flex_api/v1/plugin_configuration/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PluginConfigurationContext] = None @property @@ -101,6 +103,34 @@ async def fetch_async( flex_metadata=flex_metadata, ) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginConfigurationInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginConfigurationInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + flex_metadata=flex_metadata, + ) + @property def plugins(self) -> ConfiguredPluginList: """ @@ -137,6 +167,28 @@ def __init__(self, version: Version, sid: str): self._plugins: Optional[ConfiguredPluginList] = None + def _fetch(self, flex_metadata: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch( self, flex_metadata: Union[str, object] = values.unset ) -> PluginConfigurationInstance: @@ -147,20 +199,54 @@ def fetch( :returns: The fetched PluginConfigurationInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginConfigurationInstance and return response metadata - return PluginConfigurationInstance( + :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 @@ -172,22 +258,32 @@ async def fetch_async( :returns: The fetched PluginConfigurationInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + 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 - return PluginConfigurationInstance( + :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: @@ -219,6 +315,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PluginConfigurationInstance: :param payload: Payload response from the API """ + return PluginConfigurationInstance(self._version, payload) def __repr__(self) -> str: @@ -243,22 +340,18 @@ def __init__(self, version: Version): self._uri = "/PluginService/Configurations" - def create( + def _create( self, name: str, flex_metadata: Union[str, object] = values.unset, plugins: Union[List[object], object] = values.unset, description: Union[str, object] = values.unset, - ) -> PluginConfigurationInstance: + ) -> tuple: """ - Create the PluginConfigurationInstance - - :param name: The Flex Plugin Configuration's name. - :param flex_metadata: The Flex-Metadata HTTP request header - :param plugins: A list of objects that describe the plugin versions included in the configuration. Each object contains the sid of the plugin version. - :param description: The Flex Plugin Configuration's description. + Internal helper for create operation - :returns: The created PluginConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -275,13 +368,15 @@ def create( } ) - 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 PluginConfigurationInstance(self._version, payload) - - async def create_async( + def create( self, name: str, flex_metadata: Union[str, object] = values.unset, @@ -289,7 +384,7 @@ async def create_async( description: Union[str, object] = values.unset, ) -> PluginConfigurationInstance: """ - Asynchronously create the PluginConfigurationInstance + Create the PluginConfigurationInstance :param name: The Flex Plugin Configuration's name. :param flex_metadata: The Flex-Metadata HTTP request header @@ -298,6 +393,53 @@ async def create_async( :returns: The created PluginConfigurationInstance """ + payload, _, _ = self._create( + name=name, + flex_metadata=flex_metadata, + plugins=plugins, + description=description, + ) + return PluginConfigurationInstance(self._version, payload) + + def create_with_http_info( + self, + name: str, + flex_metadata: Union[str, object] = values.unset, + plugins: Union[List[object], object] = values.unset, + description: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the PluginConfigurationInstance and return response metadata + + :param name: The Flex Plugin Configuration's name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param plugins: A list of objects that describe the plugin versions included in the configuration. Each object contains the sid of the plugin version. + :param description: The Flex Plugin Configuration's description. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + name=name, + flex_metadata=flex_metadata, + plugins=plugins, + description=description, + ) + instance = PluginConfigurationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + name: str, + flex_metadata: Union[str, object] = values.unset, + plugins: Union[List[object], object] = values.unset, + description: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -313,12 +455,65 @@ async def create_async( } ) - 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, + 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, @@ -375,6 +570,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PluginConfigurationInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PluginConfigurationInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, flex_metadata: Union[str, object] = values.unset, @@ -396,6 +647,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( flex_metadata=flex_metadata, @@ -425,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( @@ -434,6 +687,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PluginConfigurationInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PluginConfigurationInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, flex_metadata: Union[str, object] = values.unset, @@ -461,7 +770,18 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -491,11 +811,106 @@ async def page_async( } ) + 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 + 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. diff --git a/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py b/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py index 6e54012eb0..473f86f966 100644 --- a/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py +++ b/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,7 @@ def __init__( "configuration_sid": configuration_sid, "plugin_sid": plugin_sid or self.plugin_sid, } + self._context: Optional[ConfiguredPluginContext] = None @property @@ -122,6 +124,34 @@ async def fetch_async( flex_metadata=flex_metadata, ) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ConfiguredPluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfiguredPluginInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + flex_metadata=flex_metadata, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -153,6 +183,28 @@ def __init__(self, version: Version, configuration_sid: str, plugin_sid: str): **self._solution ) + def _fetch(self, flex_metadata: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch( self, flex_metadata: Union[str, object] = values.unset ) -> ConfiguredPluginInstance: @@ -163,21 +215,56 @@ def fetch( :returns: The fetched ConfiguredPluginInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ConfiguredPluginInstance and return response metadata - return ConfiguredPluginInstance( + :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 @@ -189,23 +276,34 @@ async def fetch_async( :returns: The fetched ConfiguredPluginInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + 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 - return ConfiguredPluginInstance( + :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: """ @@ -225,6 +323,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConfiguredPluginInstance: :param payload: Payload response from the API """ + return ConfiguredPluginInstance( self._version, payload, @@ -316,6 +415,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ConfiguredPluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ConfiguredPluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, flex_metadata: Union[str, object] = values.unset, @@ -337,6 +492,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( flex_metadata=flex_metadata, @@ -366,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( @@ -375,6 +532,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ConfiguredPluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ConfiguredPluginInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, flex_metadata: Union[str, object] = values.unset, @@ -402,8 +615,19 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ConfiguredPluginPage(self._version, response, self._solution) + 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, @@ -432,10 +656,105 @@ async def page_async( } ) + 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 + 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 + ) ) - return ConfiguredPluginPage(self._version, response, self._solution) + 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: """ @@ -447,7 +766,7 @@ def get_page(self, target_url: str) -> ConfiguredPluginPage: :returns: Page of ConfiguredPluginInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ConfiguredPluginPage(self._version, response, self._solution) + return ConfiguredPluginPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ConfiguredPluginPage: """ @@ -459,7 +778,7 @@ async def get_page_async(self, target_url: str) -> ConfiguredPluginPage: :returns: Page of ConfiguredPluginInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ConfiguredPluginPage(self._version, response, self._solution) + return ConfiguredPluginPage(self._version, response, solution=self._solution) def get(self, plugin_sid: str) -> ConfiguredPluginContext: """ diff --git a/twilio/rest/flex_api/v1/plugin_configuration_archive.py b/twilio/rest/flex_api/v1/plugin_configuration_archive.py index 97d2f8120d..e880c68ec4 100644 --- a/twilio/rest/flex_api/v1/plugin_configuration_archive.py +++ b/twilio/rest/flex_api/v1/plugin_configuration_archive.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -50,6 +51,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PluginConfigurationArchiveContext] = None @property @@ -95,6 +97,34 @@ async def update_async( flex_metadata=flex_metadata, ) + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginConfigurationArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + flex_metadata=flex_metadata, + ) + + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginConfigurationArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + flex_metadata=flex_metadata, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -126,6 +156,29 @@ def __init__(self, version: Version, sid: str): **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: @@ -136,20 +189,51 @@ def update( :returns: The updated PluginConfigurationArchiveInstance """ - data = values.of({}) - headers = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = self._update(flex_metadata=flex_metadata) + return PluginConfigurationArchiveInstance( + self._version, payload, sid=self._solution["sid"] ) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginConfigurationArchiveInstance and return response metadata - return PluginConfigurationArchiveInstance( + :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 @@ -161,20 +245,28 @@ async def update_async( :returns: The updated PluginConfigurationArchiveInstance """ - data = values.of({}) - headers = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = await self._update_async(flex_metadata=flex_metadata) + return PluginConfigurationArchiveInstance( + self._version, payload, 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, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginConfigurationArchiveInstance and return response metadata - return PluginConfigurationArchiveInstance( + :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: """ diff --git a/twilio/rest/flex_api/v1/plugin_release.py b/twilio/rest/flex_api/v1/plugin_release.py index e339183297..08d3bbd00f 100644 --- a/twilio/rest/flex_api/v1/plugin_release.py +++ b/twilio/rest/flex_api/v1/plugin_release.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -47,6 +48,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PluginReleaseContext] = None @property @@ -92,6 +94,34 @@ async def fetch_async( flex_metadata=flex_metadata, ) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginReleaseInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + flex_metadata=flex_metadata, + ) + + async def fetch_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PluginReleaseInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + flex_metadata=flex_metadata, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -119,6 +149,28 @@ def __init__(self, version: Version, sid: str): } self._uri = "/PluginService/Releases/{sid}".format(**self._solution) + def _fetch(self, flex_metadata: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + def fetch( self, flex_metadata: Union[str, object] = values.unset ) -> PluginReleaseInstance: @@ -129,20 +181,54 @@ def fetch( :returns: The fetched PluginReleaseInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginReleaseInstance and return response metadata - return PluginReleaseInstance( + :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 @@ -154,22 +240,32 @@ async def fetch_async( :returns: The fetched PluginReleaseInstance """ - - data = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + 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 - return PluginReleaseInstance( + :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: """ @@ -189,6 +285,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PluginReleaseInstance: :param payload: Payload response from the API """ + return PluginReleaseInstance(self._version, payload) def __repr__(self) -> str: @@ -213,16 +310,14 @@ def __init__(self, version: Version): self._uri = "/PluginService/Releases" - def create( + def _create( self, configuration_id: str, flex_metadata: Union[str, object] = values.unset - ) -> PluginReleaseInstance: + ) -> tuple: """ - Create the PluginReleaseInstance + Internal helper for create operation - :param configuration_id: The SID or the Version of the Flex Plugin Configuration to release. - :param flex_metadata: The Flex-Metadata HTTP request header - - :returns: The created PluginReleaseInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -237,23 +332,56 @@ def create( } ) - 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 PluginReleaseInstance(self._version, payload) - - async def create_async( + def create( self, configuration_id: str, flex_metadata: Union[str, object] = values.unset ) -> PluginReleaseInstance: """ - Asynchronously create the PluginReleaseInstance + Create the PluginReleaseInstance :param configuration_id: The SID or the Version of the Flex Plugin Configuration to release. :param flex_metadata: The Flex-Metadata HTTP request header :returns: The created PluginReleaseInstance """ + payload, _, _ = self._create( + configuration_id=configuration_id, flex_metadata=flex_metadata + ) + return PluginReleaseInstance(self._version, payload) + + def create_with_http_info( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the PluginReleaseInstance and return response metadata + + :param configuration_id: The SID or the Version of the Flex Plugin Configuration to release. + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + configuration_id=configuration_id, flex_metadata=flex_metadata + ) + instance = PluginReleaseInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -267,12 +395,47 @@ async def create_async( } ) - 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, 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, @@ -329,6 +492,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PluginReleaseInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PluginReleaseInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, flex_metadata: Union[str, object] = values.unset, @@ -350,6 +569,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( flex_metadata=flex_metadata, @@ -379,6 +599,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -388,6 +609,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PluginReleaseInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PluginReleaseInstance and returns headers from first page + + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, flex_metadata: Union[str, object] = values.unset, @@ -415,7 +692,18 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -445,11 +733,106 @@ async def page_async( } ) + 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 + 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. diff --git a/twilio/rest/flex_api/v1/plugin_version_archive.py b/twilio/rest/flex_api/v1/plugin_version_archive.py index ae8d2f3dff..d2b601a828 100644 --- a/twilio/rest/flex_api/v1/plugin_version_archive.py +++ b/twilio/rest/flex_api/v1/plugin_version_archive.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( "plugin_sid": plugin_sid or self.plugin_sid, "sid": sid or self.sid, } + self._context: Optional[PluginVersionArchiveContext] = None @property @@ -107,6 +109,34 @@ async def update_async( flex_metadata=flex_metadata, ) + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginVersionArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + flex_metadata=flex_metadata, + ) + + async def update_with_http_info_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginVersionArchiveInstance with HTTP info + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + flex_metadata=flex_metadata, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -138,6 +168,29 @@ def __init__(self, version: Version, plugin_sid: str, sid: str): **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: @@ -148,23 +201,57 @@ def update( :returns: The updated PluginVersionArchiveInstance """ - data = values.of({}) - headers = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = self._update(flex_metadata=flex_metadata) + return PluginVersionArchiveInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], ) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the PluginVersionArchiveInstance and return response metadata - return PluginVersionArchiveInstance( + :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 @@ -176,23 +263,34 @@ async def update_async( :returns: The updated PluginVersionArchiveInstance """ - data = values.of({}) - headers = values.of( - { - "Flex-Metadata": flex_metadata, - } + payload, _, _ = await self._update_async(flex_metadata=flex_metadata) + return PluginVersionArchiveInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_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, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PluginVersionArchiveInstance and return response metadata - return PluginVersionArchiveInstance( + :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: """ diff --git a/twilio/rest/flex_api/v1/provisioning_status.py b/twilio/rest/flex_api/v1/provisioning_status.py index 9cc9144dcc..a13a1baab7 100644 --- a/twilio/rest/flex_api/v1/provisioning_status.py +++ b/twilio/rest/flex_api/v1/provisioning_status.py @@ -13,6 +13,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 @@ -74,6 +76,24 @@ async def fetch_async(self) -> "ProvisioningStatusInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ProvisioningStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ProvisioningStatusInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -96,6 +116,22 @@ def __init__(self, version: 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 @@ -103,16 +139,41 @@ def fetch(self) -> ProvisioningStatusInstance: :returns: The fetched ProvisioningStatusInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ProvisioningStatusInstance( + self._version, + payload, ) - return ProvisioningStatusInstance( + 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: """ @@ -121,16 +182,25 @@ async def fetch_async(self) -> ProvisioningStatusInstance: :returns: The fetched ProvisioningStatusInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ProvisioningStatusInstance( + self._version, + payload, ) - return ProvisioningStatusInstance( + 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: """ diff --git a/twilio/rest/flex_api/v1/web_channel.py b/twilio/rest/flex_api/v1/web_channel.py index a96698f8cb..0b0560cb89 100644 --- a/twilio/rest/flex_api/v1/web_channel.py +++ b/twilio/rest/flex_api/v1/web_channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -55,6 +56,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[WebChannelContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WebChannelInstance": """ Fetch the WebChannelInstance @@ -108,6 +128,24 @@ async def fetch_async(self) -> "WebChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, @@ -144,6 +182,42 @@ async def update_async( post_engagement_data=post_engagement_data, ) + def update_with_http_info( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebChannelInstance with HTTP info + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + chat_status=chat_status, + post_engagement_data=post_engagement_data, + ) + + async def update_with_http_info_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebChannelInstance with HTTP info + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + chat_status=chat_status, + post_engagement_data=post_engagement_data, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -171,6 +245,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/WebChannels/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WebChannelInstance @@ -178,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: @@ -190,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: @@ -202,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: """ @@ -221,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, @@ -246,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, @@ -274,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: """ @@ -307,6 +551,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WebChannelInstance: :param payload: Payload response from the API """ + return WebChannelInstance(self._version, payload) def __repr__(self) -> str: @@ -331,7 +576,7 @@ def __init__(self, version: Version): self._uri = "/WebChannels" - def create( + def _create( self, flex_flow_sid: str, identity: str, @@ -339,18 +584,12 @@ def create( chat_friendly_name: str, chat_unique_name: Union[str, object] = values.unset, pre_engagement_data: Union[str, object] = values.unset, - ) -> WebChannelInstance: + ) -> tuple: """ - Create the WebChannelInstance + Internal helper for create operation - :param flex_flow_sid: The SID of the Flex Flow. - :param identity: The chat identity. - :param customer_friendly_name: The chat participant's friendly name. - :param chat_friendly_name: The chat channel's friendly name. - :param chat_unique_name: The chat channel's unique name. - :param pre_engagement_data: The pre-engagement data. - - :returns: The created WebChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -365,13 +604,15 @@ def create( ) headers = values.of({"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 WebChannelInstance(self._version, payload) - - async def create_async( + def create( self, flex_flow_sid: str, identity: str, @@ -381,7 +622,7 @@ async def create_async( pre_engagement_data: Union[str, object] = values.unset, ) -> WebChannelInstance: """ - Asynchronously create the WebChannelInstance + Create the WebChannelInstance :param flex_flow_sid: The SID of the Flex Flow. :param identity: The chat identity. @@ -392,6 +633,63 @@ async def create_async( :returns: The created WebChannelInstance """ + payload, _, _ = self._create( + flex_flow_sid=flex_flow_sid, + identity=identity, + customer_friendly_name=customer_friendly_name, + chat_friendly_name=chat_friendly_name, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + ) + return WebChannelInstance(self._version, payload) + + def create_with_http_info( + self, + flex_flow_sid: str, + identity: str, + customer_friendly_name: str, + chat_friendly_name: str, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the WebChannelInstance and return response metadata + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The chat identity. + :param customer_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + flex_flow_sid=flex_flow_sid, + identity=identity, + customer_friendly_name=customer_friendly_name, + chat_friendly_name=chat_friendly_name, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + ) + instance = WebChannelInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + flex_flow_sid: str, + identity: str, + customer_friendly_name: str, + chat_friendly_name: str, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -405,12 +703,77 @@ async def create_async( ) headers = values.of({"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, + flex_flow_sid: str, + identity: str, + customer_friendly_name: str, + chat_friendly_name: str, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: + """ + Asynchronously create the WebChannelInstance + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The chat identity. + :param customer_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + + :returns: The created WebChannelInstance + """ + payload, _, _ = await self._create_async( + flex_flow_sid=flex_flow_sid, + identity=identity, + customer_friendly_name=customer_friendly_name, + chat_friendly_name=chat_friendly_name, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + ) return WebChannelInstance(self._version, payload) + async def create_with_http_info_async( + self, + flex_flow_sid: str, + identity: str, + customer_friendly_name: str, + chat_friendly_name: str, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WebChannelInstance and return response metadata + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The chat identity. + :param customer_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + flex_flow_sid=flex_flow_sid, + identity=identity, + customer_friendly_name=customer_friendly_name, + chat_friendly_name=chat_friendly_name, + chat_unique_name=chat_unique_name, + pre_engagement_data=pre_engagement_data, + ) + instance = WebChannelInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -461,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, @@ -480,6 +893,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -506,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( @@ -514,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, @@ -538,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( @@ -565,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/flex_user.py b/twilio/rest/flex_api/v2/flex_user.py index 1acc75a8a8..70ed7b7ac6 100644 --- a/twilio/rest/flex_api/v2/flex_user.py +++ b/twilio/rest/flex_api/v2/flex_user.py @@ -13,8 +13,9 @@ """ from datetime import datetime -from typing import Any, Dict, Optional -from twilio.base import deserialize +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -30,11 +31,10 @@ class FlexUserInstance(InstanceResource): :ivar worker_sid: The unique SID identifier of the worker. :ivar workspace_sid: The unique SID identifier of the workspace. :ivar flex_team_sid: The unique SID identifier of the Flex Team. - :ivar first_name: First name of the User. - :ivar last_name: Last name of the User. :ivar username: Username of the User. :ivar email: Email of the User. - :ivar friendly_name: Friendly name of the User. + :ivar locale: The locale preference of the user. + :ivar roles: The roles of the user. :ivar created_date: The date that this user was created, given in ISO 8601 format. :ivar updated_date: The date that this user was updated, given in ISO 8601 format. :ivar version: The current version of the user. @@ -57,11 +57,10 @@ def __init__( self.worker_sid: Optional[str] = payload.get("worker_sid") self.workspace_sid: Optional[str] = payload.get("workspace_sid") self.flex_team_sid: Optional[str] = payload.get("flex_team_sid") - self.first_name: Optional[str] = payload.get("first_name") - self.last_name: Optional[str] = payload.get("last_name") self.username: Optional[str] = payload.get("username") self.email: Optional[str] = payload.get("email") - self.friendly_name: Optional[str] = payload.get("friendly_name") + self.locale: Optional[str] = payload.get("locale") + self.roles: Optional[List[str]] = payload.get("roles") self.created_date: Optional[datetime] = deserialize.iso8601_datetime( payload.get("created_date") ) @@ -75,6 +74,7 @@ def __init__( "instance_sid": instance_sid or self.instance_sid, "flex_user_sid": flex_user_sid or self.flex_user_sid, } + self._context: Optional[FlexUserContext] = None @property @@ -111,6 +111,108 @@ async def fetch_async(self) -> "FlexUserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlexUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlexUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + 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 @@ -129,7 +231,7 @@ def __init__(self, version: Version, instance_sid: str, flex_user_sid: str): :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 to be retrieved. + :param flex_user_sid: The unique id for the flex user. """ super().__init__(version) @@ -142,6 +244,22 @@ def __init__(self, version: Version, instance_sid: str, flex_user_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) -> FlexUserInstance: """ Fetch the FlexUserInstance @@ -149,18 +267,45 @@ def fetch(self) -> FlexUserInstance: :returns: The fetched FlexUserInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], ) - return FlexUserInstance( + 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: """ @@ -169,12 +314,157 @@ async def fetch_async(self) -> 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 - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + :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, @@ -182,6 +472,32 @@ async def fetch_async(self) -> FlexUserInstance: 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 @@ -208,7 +524,7 @@ 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 to be retrieved. + :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 @@ -219,7 +535,7 @@ 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 to be retrieved. + :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 diff --git a/twilio/rest/flex_api/v2/web_channels.py b/twilio/rest/flex_api/v2/web_channels.py index 153f59cae9..f25f907348 100644 --- a/twilio/rest/flex_api/v2/web_channels.py +++ b/twilio/rest/flex_api/v2/web_channels.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -55,24 +56,20 @@ def __init__(self, version: Version): self._uri = "/WebChats" - def create( + def _create( self, address_sid: str, ui_version: Union[str, object] = values.unset, chat_friendly_name: Union[str, object] = values.unset, customer_friendly_name: Union[str, object] = values.unset, pre_engagement_data: Union[str, object] = values.unset, - ) -> WebChannelsInstance: + identity: Union[str, object] = values.unset, + ) -> tuple: """ - Create the WebChannelsInstance + Internal helper for create operation - :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. - :param ui_version: The Ui-Version HTTP request header - :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. - :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. - :param pre_engagement_data: The pre-engagement data. - - :returns: The created WebChannelsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -81,6 +78,7 @@ def create( "ChatFriendlyName": chat_friendly_name, "CustomerFriendlyName": customer_friendly_name, "PreEngagementData": pre_engagement_data, + "Identity": identity, } ) headers = values.of( @@ -90,31 +88,92 @@ def create( } ) - 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 WebChannelsInstance(self._version, payload) - - async def create_async( + def create( self, address_sid: str, ui_version: Union[str, object] = values.unset, chat_friendly_name: Union[str, object] = values.unset, customer_friendly_name: Union[str, object] = values.unset, pre_engagement_data: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, ) -> WebChannelsInstance: """ - Asynchronously create the WebChannelsInstance + Create the WebChannelsInstance :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. :param ui_version: The Ui-Version HTTP request header :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. :param pre_engagement_data: The pre-engagement data. + :param identity: The Identity of the guest user. See the [Conversation User Resource](https://www.twilio.com/docs/conversations/api/user-resource) for an example. :returns: The created WebChannelsInstance """ + payload, _, _ = self._create( + address_sid=address_sid, + ui_version=ui_version, + chat_friendly_name=chat_friendly_name, + customer_friendly_name=customer_friendly_name, + pre_engagement_data=pre_engagement_data, + identity=identity, + ) + return WebChannelsInstance(self._version, payload) + + def create_with_http_info( + self, + address_sid: str, + ui_version: Union[str, object] = values.unset, + chat_friendly_name: Union[str, object] = values.unset, + customer_friendly_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the WebChannelsInstance and return response metadata + + :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. + :param ui_version: The Ui-Version HTTP request header + :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. + :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. + :param pre_engagement_data: The pre-engagement data. + :param identity: The Identity of the guest user. See the [Conversation User Resource](https://www.twilio.com/docs/conversations/api/user-resource) for an example. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + address_sid=address_sid, + ui_version=ui_version, + chat_friendly_name=chat_friendly_name, + customer_friendly_name=customer_friendly_name, + pre_engagement_data=pre_engagement_data, + identity=identity, + ) + instance = WebChannelsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + address_sid: str, + ui_version: Union[str, object] = values.unset, + chat_friendly_name: Union[str, object] = values.unset, + customer_friendly_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -122,6 +181,7 @@ async def create_async( "ChatFriendlyName": chat_friendly_name, "CustomerFriendlyName": customer_friendly_name, "PreEngagementData": pre_engagement_data, + "Identity": identity, } ) headers = values.of( @@ -131,12 +191,77 @@ async def create_async( } ) - 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, + address_sid: str, + ui_version: Union[str, object] = values.unset, + chat_friendly_name: Union[str, object] = values.unset, + customer_friendly_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + ) -> WebChannelsInstance: + """ + Asynchronously create the WebChannelsInstance + + :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. + :param ui_version: The Ui-Version HTTP request header + :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. + :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. + :param pre_engagement_data: The pre-engagement data. + :param identity: The Identity of the guest user. See the [Conversation User Resource](https://www.twilio.com/docs/conversations/api/user-resource) for an example. + + :returns: The created WebChannelsInstance + """ + payload, _, _ = await self._create_async( + address_sid=address_sid, + ui_version=ui_version, + chat_friendly_name=chat_friendly_name, + customer_friendly_name=customer_friendly_name, + pre_engagement_data=pre_engagement_data, + identity=identity, + ) return WebChannelsInstance(self._version, payload) + async def create_with_http_info_async( + self, + address_sid: str, + ui_version: Union[str, object] = values.unset, + chat_friendly_name: Union[str, object] = values.unset, + customer_friendly_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WebChannelsInstance and return response metadata + + :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. + :param ui_version: The Ui-Version HTTP request header + :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. + :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. + :param pre_engagement_data: The pre-engagement data. + :param identity: The Identity of the guest user. See the [Conversation User Resource](https://www.twilio.com/docs/conversations/api/user-resource) for an example. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + address_sid=address_sid, + ui_version=ui_version, + chat_friendly_name=chat_friendly_name, + customer_friendly_name=customer_friendly_name, + pre_engagement_data=pre_engagement_data, + identity=identity, + ) + instance = WebChannelsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/frontline_api/v1/user.py b/twilio/rest/frontline_api/v1/user.py index 8c9dd93853..f3cb7f3b25 100644 --- a/twilio/rest/frontline_api/v1/user.py +++ b/twilio/rest/frontline_api/v1/user.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -87,6 +89,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -135,6 +155,54 @@ async def update_async( is_available=is_available, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -162,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 @@ -169,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: """ @@ -188,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, @@ -217,6 +369,54 @@ 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, @@ -225,14 +425,15 @@ def update( "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, @@ -251,22 +452,39 @@ async def update_async( :returns: The updated UserInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Avatar": avatar, - "State": state, - "IsAvailable": serialize.boolean_to_string(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: """ 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 458122cec7..e2d5c3328d 100644 --- a/twilio/rest/insights/InsightsBase.py +++ b/twilio/rest/insights/InsightsBase.py @@ -14,6 +14,8 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.insights.v1 import V1 +from twilio.rest.insights.v2 import V2 +from twilio.rest.insights.v3 import V3 class InsightsBase(Domain): @@ -26,6 +28,8 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://insights.twilio.com") self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + self._v3: Optional[V3] = None @property def v1(self) -> V1: @@ -36,6 +40,24 @@ def v1(self) -> V1: self._v1 = V1(self) return self._v1 + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Insights + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Insights + """ + if self._v3 is None: + self._v3 = V3(self) + return self._v3 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/insights/v1/call/__init__.py b/twilio/rest/insights/v1/call/__init__.py index ff628b7d06..89516703cd 100644 --- a/twilio/rest/insights/v1/call/__init__.py +++ b/twilio/rest/insights/v1/call/__init__.py @@ -13,6 +13,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 @@ -43,6 +45,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CallContext] = None @property @@ -78,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: """ @@ -138,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 @@ -145,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: """ @@ -164,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: diff --git a/twilio/rest/insights/v1/call/annotation.py b/twilio/rest/insights/v1/call/annotation.py index d560003c0a..5bda909b68 100644 --- a/twilio/rest/insights/v1/call/annotation.py +++ b/twilio/rest/insights/v1/call/annotation.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -69,6 +70,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): self._solution = { "call_sid": call_sid, } + self._context: Optional[AnnotationContext] = None @property @@ -104,6 +106,24 @@ async def fetch_async(self) -> "AnnotationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AnnotationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AnnotationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, @@ -174,6 +194,76 @@ async def update_async( incident=incident, ) + def update_with_http_info( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the AnnotationInstance with HTTP info + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + + async def update_with_http_info_async( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AnnotationInstance with HTTP info + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,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 @@ -208,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: """ @@ -227,17 +359,67 @@ 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( + 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 helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "AnsweredBy": answered_by, + "ConnectivityIssue": connectivity_issue, + "QualityIssues": quality_issues, + "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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) def update( self, @@ -264,6 +446,77 @@ def update( :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"] + ) + + 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 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 = 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, @@ -275,15 +528,14 @@ def update( "Incident": incident, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return AnnotationInstance( - self._version, payload, call_sid=self._solution["call_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( @@ -311,27 +563,57 @@ async def update_async( :returns: The updated AnnotationInstance """ - data = values.of( - { - "AnsweredBy": answered_by, - "ConnectivityIssue": connectivity_issue, - "QualityIssues": quality_issues, - "Spam": serialize.boolean_to_string(spam), - "CallScore": call_score, - "Comment": comment, - "Incident": incident, - } + 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, ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + return AnnotationInstance( + self._version, payload, call_sid=self._solution["call_sid"] ) - return AnnotationInstance( + 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: """ diff --git a/twilio/rest/insights/v1/call/call_summary.py b/twilio/rest/insights/v1/call/call_summary.py index 0e256b36c8..edb1ba1178 100644 --- a/twilio/rest/insights/v1/call/call_summary.py +++ b/twilio/rest/insights/v1/call/call_summary.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -47,6 +48,7 @@ class CallType(object): SIP = "sip" TRUNKING = "trunking" CLIENT = "client" + WHATSAPP = "whatsapp" class ProcessingState(object): COMPLETE = "complete" @@ -64,18 +66,18 @@ class ProcessingState(object): :ivar end_time: The time at which the Call was ended, given in ISO 8601 format. :ivar duration: Duration between when the call was initiated and the call was ended :ivar connect_duration: Duration between when the call was answered and when it ended - :ivar _from: The calling party. - :ivar to: The called party. - :ivar carrier_edge: Contains metrics and properties for the Twilio media gateway of a PSTN call. - :ivar client_edge: Contains metrics and properties for the Twilio media gateway of a Client call. - :ivar sdk_edge: Contains metrics and properties for the SDK sensor library for Client calls. - :ivar sip_edge: Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. + :ivar _from: `object` The calling party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + :ivar to: `object` The called party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + :ivar carrier_edge: `object` Contains metrics and properties for the Twilio media gateway of a PSTN call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar client_edge: `object` Contains metrics and properties for the Twilio media gateway of a Client call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sdk_edge: `object` Contains metrics and properties for the SDK sensor library for Client calls. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sip_edge: `object` Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. :ivar tags: Tags applied to calls by Voice Insights analysis indicating a condition that could result in subjective degradation of the call quality. :ivar url: The URL of this resource. - :ivar attributes: Attributes capturing call-flow-specific details. - :ivar properties: Contains edge-agnostic call-level details. - :ivar trust: Contains trusted communications details including Branded Call and verified caller ID. - :ivar annotation: Programmatically labeled annotations for the Call. Developers can update the Call Summary records with Annotation during or after a Call. Annotations can be updated as long as the Call Summary record is addressable via the API. + :ivar attributes: `object` Attributes capturing call-flow-specific details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#attributes-object) for the object properties. + :ivar properties: `object` Contains edge-agnostic call-level details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#properties-object) for the object properties. + :ivar trust: `object` Contains trusted communications details including Branded Call and verified caller ID. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#trust-object) for the object properties. + :ivar annotation: `object` Programmatically labeled annotations for the Call. Developers can update the Call Summary records with Annotation during or after a Call. Annotations can be updated as long as the Call Summary record is addressable via the API. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#annotation-object) for the object properties. """ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): @@ -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 @@ -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 @@ -202,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: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + Internal helper for fetch operation - :returns: The fetched CallSummaryInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "ProcessingState": processing_state, } ) - 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: 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 diff --git a/twilio/rest/insights/v1/call/event.py b/twilio/rest/insights/v1/call/event.py index 89734f110a..ca9b99ccc6 100644 --- a/twilio/rest/insights/v1/call/event.py +++ b/twilio/rest/insights/v1/call/event.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -45,10 +46,10 @@ class TwilioEdge(object): :ivar group: Event group. :ivar level: :ivar name: Event name. - :ivar carrier_edge: Represents the connection between Twilio and our immediate carrier partners. The events here describe the call lifecycle as reported by Twilio's carrier media gateways. - :ivar sip_edge: Represents the Twilio media gateway for SIP interface and SIP trunking calls. The events here describe the call lifecycle as reported by Twilio's public media gateways. - :ivar sdk_edge: Represents the Voice SDK running locally in the browser or in the Android/iOS application. The events here are emitted by the Voice SDK in response to certain call progress events, network changes, or call quality conditions. - :ivar client_edge: Represents the Twilio media gateway for Client calls. The events here describe the call lifecycle as reported by Twilio's Voice SDK media gateways. + :ivar carrier_edge: `object` Represents the connection between Twilio and our immediate carrier partners. The events here describe the call lifecycle as reported by Twilio's carrier media gateways. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sip_edge: `object` Represents the Twilio media gateway for SIP interface and SIP trunking calls. The events here describe the call lifecycle as reported by Twilio's public media gateways. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sdk_edge: `object` Represents the Voice SDK running locally in the browser or in the Android/iOS application. The events here are emitted by the Voice SDK in response to certain call progress events, network changes, or call quality conditions. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar client_edge: `object` Represents the Twilio media gateway for Client calls. The events here describe the call lifecycle as reported by Twilio's Voice SDK media gateways. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. """ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): @@ -88,6 +89,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EventInstance: :param payload: Payload response from the API """ + return EventInstance( self._version, payload, call_sid=self._solution["call_sid"] ) @@ -173,6 +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, @@ -194,6 +252,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( edge=edge, @@ -223,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( @@ -232,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, @@ -259,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, @@ -289,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: """ @@ -304,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: """ @@ -316,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 3cf9decc53..7cf72240b7 100644 --- a/twilio/rest/insights/v1/call/metric.py +++ b/twilio/rest/insights/v1/call/metric.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -85,6 +86,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MetricInstance: :param payload: Payload response from the API """ + return MetricInstance( self._version, payload, call_sid=self._solution["call_sid"] ) @@ -176,6 +178,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MetricInstance and returns headers from first page + + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + edge=edge, direction=direction, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams MetricInstance and returns headers from first page + + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + edge=edge, direction=direction, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, edge: Union["MetricInstance.TwilioEdge", object] = values.unset, @@ -199,6 +261,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( edge=edge, @@ -231,6 +294,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -241,6 +305,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MetricInstance and returns headers from first page + + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + edge=edge, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists MetricInstance and returns headers from first page + + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + edge=edge, + direction=direction, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, edge: Union["MetricInstance.TwilioEdge", object] = values.unset, @@ -271,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, @@ -304,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: """ @@ -319,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: """ @@ -331,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 f68744eefc..c1de69c6d5 100644 --- a/twilio/rest/insights/v1/call_summaries.py +++ b/twilio/rest/insights/v1/call_summaries.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -48,6 +49,7 @@ class CallType(object): SIP = "sip" TRUNKING = "trunking" CLIENT = "client" + WHATSAPP = "whatsapp" class ProcessingState(object): COMPLETE = "complete" @@ -75,18 +77,18 @@ class SortBy(object): :ivar end_time: The time at which the Call was ended, given in ISO 8601 format. :ivar duration: Duration between when the call was initiated and the call was ended :ivar connect_duration: Duration between when the call was answered and when it ended - :ivar _from: The calling party. - :ivar to: The called party. - :ivar carrier_edge: Contains metrics and properties for the Twilio media gateway of a PSTN call. - :ivar client_edge: Contains metrics and properties for the Twilio media gateway of a Client call. - :ivar sdk_edge: Contains metrics and properties for the SDK sensor library for Client calls. - :ivar sip_edge: Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. + :ivar _from: `object` The calling party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + :ivar to: `object` The called party. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#tofrom-object) for the object properties. + :ivar carrier_edge: `object` Contains metrics and properties for the Twilio media gateway of a PSTN call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar client_edge: `object` Contains metrics and properties for the Twilio media gateway of a Client call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sdk_edge: `object` Contains metrics and properties for the SDK sensor library for Client calls. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. + :ivar sip_edge: `object` Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#edges-and-their-properties) for the object properties. :ivar tags: Tags applied to calls by Voice Insights analysis indicating a condition that could result in subjective degradation of the call quality. :ivar url: The URL of this resource. - :ivar attributes: Attributes capturing call-flow-specific details. - :ivar properties: Contains edge-agnostic call-level details. - :ivar trust: Contains trusted communications details including Branded Call and verified caller ID. - :ivar annotation: + :ivar attributes: `object` Attributes capturing call-flow-specific details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#attributes-object) for the object properties. + :ivar properties: `object` Contains edge-agnostic call-level details. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#properties-object) for the object properties. + :ivar trust: `object` Contains trusted communications details including Branded Call and verified caller ID. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#trust-object) for the object properties. + :ivar annotation: `object` Programmatically labeled annotations for the Call. Developers can update the Call Summary records with Annotation during or after a Call. Annotations can be updated as long as the Call Summary record is addressable via the API. See [Details: Call Summary](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-summary#annotation-object) for the object properties. """ def __init__(self, version: Version, payload: Dict[str, Any]): @@ -150,6 +152,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CallSummariesInstance: :param payload: Payload response from the API """ + return CallSummariesInstance(self._version, payload) def __repr__(self) -> str: @@ -182,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, @@ -202,6 +204,19 @@ def stream( 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]: @@ -217,8 +232,7 @@ def stream( :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 branded: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. - :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR. + :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. @@ -235,6 +249,19 @@ def stream( :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 @@ -252,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, @@ -270,6 +296,19 @@ def stream( 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"], ) @@ -283,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, @@ -303,6 +341,19 @@ async def stream_async( 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]: @@ -318,8 +369,7 @@ async def stream_async( :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 branded: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. - :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR. + :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. @@ -336,6 +386,19 @@ async def stream_async( :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 @@ -353,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, @@ -371,11 +433,296 @@ async def stream_async( 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, @@ -384,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, @@ -404,6 +750,19 @@ def list( 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]: @@ -418,8 +777,7 @@ def list( :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 branded: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. - :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR. + :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. @@ -436,6 +794,19 @@ def list( :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 @@ -445,6 +816,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( from_=from_, @@ -453,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, @@ -471,6 +842,19 @@ def list( 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, ) @@ -484,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, @@ -504,6 +887,19 @@ async def list_async( 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]: @@ -518,8 +914,7 @@ async def list_async( :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 branded: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. - :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR. + :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. @@ -536,6 +931,19 @@ async def list_async( :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 @@ -545,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( @@ -554,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, @@ -572,12 +980,25 @@ async def list_async( 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 page( + def list_with_http_info( self, from_: Union[str, object] = values.unset, to: Union[str, object] = values.unset, @@ -585,7 +1006,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, @@ -605,56 +1025,350 @@ def page( quality_issue_annotation: Union[str, object] = values.unset, spam_annotation: Union[bool, object] = values.unset, call_score_annotation: Union[str, object] = values.unset, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> CallSummariesPage: + 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: """ - Retrieve a single page of CallSummariesInstance records from the API. - Request is executed immediately + Lists CallSummariesInstance and returns headers from first page - :param from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. - :param to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. - :param from_carrier: An origination carrier. - :param to_carrier: A destination carrier. - :param from_country_code: A source country code based on phone number in From. - :param to_country_code: A destination country code. Based on phone number in To. - :param branded: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. - :param verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR. - :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 page_token: PageToken provided by the API - :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 CallSummariesInstance + :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 """ - data = values.of( - { - "From": from_, - "To": to, - "FromCarrier": from_carrier, - "ToCarrier": to_carrier, - "FromCountryCode": from_country_code, - "ToCountryCode": to_country_code, - "Branded": serialize.boolean_to_string(branded), - "VerifiedCaller": serialize.boolean_to_string(verified_caller), - "HasTag": serialize.boolean_to_string(has_tag), - "StartTime": start_time, + generator, status_code, headers = self.stream_with_http_info( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CallSummariesInstance and returns headers from first page + + + :param str from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str from_carrier: An origination carrier. + :param str to_carrier: A destination carrier. + :param str from_country_code: A source country code based on phone number in From. + :param str to_country_code: A destination country code. Based on phone number in To. + :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param bool has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param str start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param str end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param str call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param str call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param str direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param "CallSummariesInstance.ProcessingStateRequest" processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param "CallSummariesInstance.SortBy" sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param str subaccount: A unique SID identifier of a Subaccount. + :param bool abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param "CallSummariesInstance.AnsweredBy" answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param str answered_by_annotation: Either machine or human. + :param str connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param str quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param bool spam_annotation: A boolean flag indicating spam calls. + :param str call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param bool branded_logo: Indicates whether the branded logo was displayed during the in_brand branded call. Possible values are true (logo was present) or false (logo was not present). + :param str branded_type: Indicates whether the Branded Call is in_band vs out_of_band. + :param str branded_use_case: Specifies the user-defined purpose for the call, as provided during the setup of in_band branded calling. + :param str branded_call_reason: Specifies the user-defined reason for the call, which will be displayed to the end user on their mobile device during an in_band branded call. + :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param str business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param str business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param str business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + branded_logo=branded_logo, + branded_type=branded_type, + branded_use_case=branded_use_case, + branded_call_reason=branded_call_reason, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + branded_logo: Union[bool, object] = values.unset, + branded_type: Union[str, object] = values.unset, + branded_use_case: Union[str, object] = values.unset, + branded_call_reason: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CallSummariesPage: + """ + Retrieve a single page of CallSummariesInstance records from the API. + Request is executed immediately + + :param from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param from_carrier: An origination carrier. + :param to_carrier: A destination carrier. + :param from_country_code: A source country code based on phone number in From. + :param to_country_code: A destination country code. Based on phone number in To. + :param verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :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: Page of CallSummariesInstance + """ + 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, @@ -669,13 +1383,34 @@ def page( "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( @@ -686,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, @@ -706,6 +1440,19 @@ async def page_async( 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, @@ -720,8 +1467,7 @@ async def page_async( :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 branded: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. - :param verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR. + :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. @@ -738,6 +1484,19 @@ async def page_async( :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 @@ -752,7 +1511,6 @@ async def page_async( "ToCarrier": to_carrier, "FromCountryCode": from_country_code, "ToCountryCode": to_country_code, - "Branded": serialize.boolean_to_string(branded), "VerifiedCaller": serialize.boolean_to_string(verified_caller), "HasTag": serialize.boolean_to_string(has_tag), "StartTime": start_time, @@ -770,17 +1528,330 @@ async def page_async( "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 1ee8c09dc8..72a54a8e96 100644 --- a/twilio/rest/insights/v1/conference/__init__.py +++ b/twilio/rest/insights/v1/conference/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,12 +52,14 @@ class ProcessingState(object): class Region(object): US1 = "us1" + US2 = "us2" AU1 = "au1" BR1 = "br1" IE1 = "ie1" JP1 = "jp1" SG1 = "sg1" DE1 = "de1" + IN1 = "in1" class Tag(object): INVALID_REQUESTED_REGION = "invalid_requested_region" @@ -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. @@ -160,6 +164,7 @@ def __init__( 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: """ @@ -231,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 @@ -238,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: """ @@ -257,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: @@ -299,6 +374,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConferenceInstance: :param payload: Payload response from the API """ + return ConferenceInstance(self._version, payload) def __repr__(self) -> str: @@ -437,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, @@ -476,6 +664,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( conference_sid=conference_sid, @@ -532,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( @@ -550,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, @@ -604,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( @@ -661,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 68faa690b3..ce953db174 100644 --- a/twilio/rest/insights/v1/conference/conference_participant.py +++ b/twilio/rest/insights/v1/conference/conference_participant.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ class Region(object): JP1 = "jp1" SG1 = "sg1" DE1 = "de1" + IN1 = "in1" """ :ivar participant_sid: SID for this participant. @@ -160,6 +162,7 @@ def __init__( "conference_sid": conference_sid, "participant_sid": participant_sid or self.participant_sid, } + self._context: Optional[ConferenceParticipantContext] = None @property @@ -214,6 +217,42 @@ async def fetch_async( metrics=metrics, ) + def fetch_with_http_info( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the ConferenceParticipantInstance with HTTP info + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + events=events, + metrics=metrics, + ) + + async def fetch_with_http_info_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConferenceParticipantInstance with HTTP info + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + events=events, + metrics=metrics, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -247,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, @@ -277,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) - data = values.of( + async def _fetch_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Events": events, "Metrics": metrics, } ) - 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, @@ -309,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 @@ -327,6 +446,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConferenceParticipantInstance :param payload: Payload response from the API """ + return ConferenceParticipantInstance( self._version, payload, conference_sid=self._solution["conference_sid"] ) @@ -432,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, @@ -457,6 +647,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( participant_sid=participant_sid, @@ -492,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( @@ -503,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, @@ -536,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, @@ -572,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 ) - return ConferenceParticipantPage(self._version, response, self._solution) + + def page_with_http_info( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param participant_sid: The unique SID identifier of the Participant. + :param label: User-specified label for a participant. + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConferenceParticipantPage, status code, and headers + """ + data = values.of( + { + "ParticipantSid": participant_sid, + "Label": label, + "Events": events, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ConferenceParticipantPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param participant_sid: The unique SID identifier of the Participant. + :param label: User-specified label for a participant. + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with ConferenceParticipantPage, status code, and headers + """ + data = values.of( + { + "ParticipantSid": participant_sid, + "Label": label, + "Events": events, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ConferenceParticipantPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ConferenceParticipantPage: """ @@ -587,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: """ @@ -599,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 7361018e23..c754e43850 100644 --- a/twilio/rest/insights/v1/room/__init__.py +++ b/twilio/rest/insights/v1/room/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -29,6 +30,7 @@ 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: """ @@ -241,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 @@ -248,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: """ @@ -267,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: @@ -309,6 +384,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoomInstance: :param payload: Payload response from the API """ + return RoomInstance(self._version, payload) def __repr__(self) -> str: @@ -417,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, @@ -446,6 +604,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( room_type=room_type, @@ -487,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( @@ -500,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, @@ -539,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( @@ -581,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 0f6617f549..9ae8554b95 100644 --- a/twilio/rest/insights/v1/room/participant.py +++ b/twilio/rest/insights/v1/room/participant.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -28,6 +29,7 @@ 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" @@ -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 @@ -182,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 @@ -189,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: """ @@ -209,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: """ @@ -240,6 +317,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: :param payload: Payload response from the API """ + return ParticipantInstance( self._version, payload, room_sid=self._solution["room_sid"] ) @@ -321,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, @@ -340,6 +468,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -366,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( @@ -374,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, @@ -398,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, @@ -425,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: """ @@ -440,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: """ @@ -452,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 c385fc424e..daf49229a9 100644 --- a/twilio/rest/insights/v1/setting.py +++ b/twilio/rest/insights/v1/setting.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -80,6 +81,34 @@ async def fetch_async( subaccount_sid=subaccount_sid, ) + def fetch_with_http_info( + self, subaccount_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the SettingInstance with HTTP info + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + subaccount_sid=subaccount_sid, + ) + + async def fetch_with_http_info_async( + self, subaccount_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SettingInstance with HTTP info + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + subaccount_sid=subaccount_sid, + ) + def update( self, advanced_features: Union[bool, object] = values.unset, @@ -122,6 +151,48 @@ async def update_async( subaccount_sid=subaccount_sid, ) + def update_with_http_info( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SettingInstance with HTTP info + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + + async def update_with_http_info_async( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SettingInstance with HTTP info + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -144,6 +215,28 @@ 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: @@ -154,18 +247,51 @@ def fetch( :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( @@ -178,20 +304,59 @@ async def fetch_async( :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( @@ -209,6 +374,49 @@ def update( :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": serialize.boolean_to_string(advanced_features), @@ -216,14 +424,15 @@ def update( "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, @@ -240,21 +449,35 @@ async def update_async( :returns: The updated SettingInstance """ - data = values.of( - { - "AdvancedFeatures": serialize.boolean_to_string(advanced_features), - "VoiceTrace": serialize.boolean_to_string(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: """ 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 index 0546bc15ae..937e497fe9 100644 --- a/twilio/rest/intelligence/IntelligenceBase.py +++ b/twilio/rest/intelligence/IntelligenceBase.py @@ -14,6 +14,7 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.intelligence.v2 import V2 +from twilio.rest.intelligence.v3 import V3 class IntelligenceBase(Domain): @@ -26,6 +27,7 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://intelligence.twilio.com") self._v2: Optional[V2] = None + self._v3: Optional[V3] = None @property def v2(self) -> V2: @@ -36,6 +38,15 @@ def v2(self) -> V2: self._v2 = V2(self) return self._v2 + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Intelligence + """ + if self._v3 is None: + self._v3 = V3(self) + return self._v3 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/intelligence/v2/custom_operator.py b/twilio/rest/intelligence/v2/custom_operator.py index af5239b124..899e6e0c6a 100644 --- a/twilio/rest/intelligence/v2/custom_operator.py +++ b/twilio/rest/intelligence/v2/custom_operator.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -29,6 +30,8 @@ class Availability(object): BETA = "beta" PUBLIC = "public" RETIRED = "retired" + GENERAL_AVAILABILITY = "general-availability" + DEPRECATED = "deprecated" """ :ivar account_sid: The unique SID identifier of the Account the Custom Operator belongs to. @@ -72,6 +75,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CustomOperatorContext] = None @property @@ -107,6 +111,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomOperatorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomOperatorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CustomOperatorInstance": """ Fetch the CustomOperatorInstance @@ -125,6 +147,24 @@ async def fetch_async(self) -> "CustomOperatorInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomOperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomOperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: str, @@ -167,6 +207,48 @@ async def update_async( if_match=if_match, ) + def update_with_http_info( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CustomOperatorInstance with HTTP info + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + config=config, + if_match=if_match, + ) + + async def update_with_http_info_async( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CustomOperatorInstance with HTTP info + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + config=config, + if_match=if_match, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -194,6 +276,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Operators/Custom/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CustomOperatorInstance @@ -201,9 +297,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 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: @@ -213,9 +331,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 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: @@ -225,17 +367,43 @@ def fetch(self) -> CustomOperatorInstance: :returns: The fetched CustomOperatorInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CustomOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CustomOperatorInstance( + 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: """ @@ -244,17 +412,61 @@ async def fetch_async(self) -> CustomOperatorInstance: :returns: The fetched CustomOperatorInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CustomOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CustomOperatorInstance( + 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, @@ -271,24 +483,68 @@ def update( :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-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 - payload = self._version.update( + 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 CustomOperatorInstance(self._version, payload, sid=self._solution["sid"]) - async def update_async( self, friendly_name: str, @@ -304,23 +560,33 @@ async def update_async( :returns: The updated CustomOperatorInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Config": serialize.object(config), - } - ) - headers = values.of( - { - "If-Match": if_match, - } + payload, _, _ = await self._update_async( + friendly_name=friendly_name, config=config, if_match=if_match ) + return CustomOperatorInstance(self._version, payload, 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, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CustomOperatorInstance and return response metadata - return CustomOperatorInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -340,6 +606,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CustomOperatorInstance: :param payload: Payload response from the API """ + return CustomOperatorInstance(self._version, payload) def __repr__(self) -> str: @@ -364,17 +631,12 @@ def __init__(self, version: Version): self._uri = "/Operators/Custom" - def create( - self, friendly_name: str, operator_type: str, config: object - ) -> CustomOperatorInstance: + def _create(self, friendly_name: str, operator_type: str, config: object) -> tuple: """ - Create the CustomOperatorInstance + Internal helper for create operation - :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 + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -386,17 +648,19 @@ def create( ) headers = values.of({"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 CustomOperatorInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, operator_type: str, config: object ) -> CustomOperatorInstance: """ - Asynchronously create the CustomOperatorInstance + Create the CustomOperatorInstance :param friendly_name: A human readable description of the new Operator, up to 64 characters. :param operator_type: Operator Type for this Operator. References an existing Operator Type resource. @@ -404,6 +668,38 @@ async def create_async( :returns: The created CustomOperatorInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, operator_type=operator_type, config=config + ) + return CustomOperatorInstance(self._version, payload) + + def create_with_http_info( + self, friendly_name: str, operator_type: str, config: object + ) -> ApiResponse: + """ + Create the CustomOperatorInstance and return response metadata + + :param friendly_name: A human readable description of the new Operator, up to 64 characters. + :param operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :param config: Operator configuration, following the schema defined by the Operator Type. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, operator_type=operator_type, config=config + ) + instance = CustomOperatorInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, operator_type: str, config: object + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -414,12 +710,49 @@ async def create_async( ) headers = values.of({"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, 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[ @@ -490,6 +823,74 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CustomOperatorInstance and returns headers from first page + + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CustomOperatorInstance and returns headers from first page + + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, availability: Union[ @@ -515,6 +916,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( availability=availability, @@ -549,6 +951,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -559,6 +962,72 @@ async def list_async( ) ] + def list_with_http_info( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CustomOperatorInstance and returns headers from first page + + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CustomOperatorInstance and returns headers from first page + + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, availability: Union[ @@ -591,7 +1060,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 CustomOperatorPage(self._version, response) async def page_async( @@ -626,11 +1101,101 @@ async def page_async( } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + response = await self._version.page_async( - method="GET", uri=self._uri, params=data + 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. diff --git a/twilio/rest/intelligence/v2/operator.py b/twilio/rest/intelligence/v2/operator.py index 6618c4a6c0..10c2ea5d5b 100644 --- a/twilio/rest/intelligence/v2/operator.py +++ b/twilio/rest/intelligence/v2/operator.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -28,6 +29,8 @@ class Availability(object): INTERNAL = "internal" BETA = "beta" PUBLIC = "public" + DEPRECATED = "deprecated" + GENERAL_AVAILABILITY = "general-availability" RETIRED = "retired" """ @@ -72,6 +75,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[OperatorContext] = None @property @@ -107,6 +111,24 @@ async def fetch_async(self) -> "OperatorInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -134,6 +156,22 @@ def __init__(self, version: Version, sid: str): } 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 @@ -141,17 +179,43 @@ def fetch(self) -> OperatorInstance: :returns: The fetched OperatorInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return OperatorInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return OperatorInstance( + 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: """ @@ -160,17 +224,27 @@ async def fetch_async(self) -> OperatorInstance: :returns: The fetched OperatorInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return OperatorInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return OperatorInstance( + 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: """ @@ -190,6 +264,7 @@ def get_instance(self, payload: Dict[str, Any]) -> OperatorInstance: :param payload: Payload response from the API """ + return OperatorInstance(self._version, payload) def __repr__(self) -> str: @@ -280,6 +355,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OperatorInstance and returns headers from first page + + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OperatorInstance and returns headers from first page + + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, availability: Union["OperatorInstance.Availability", object] = values.unset, @@ -303,6 +442,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( availability=availability, @@ -335,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( @@ -345,6 +486,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OperatorInstance and returns headers from first page + + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OperatorInstance and returns headers from first page + + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, availability: Union["OperatorInstance.Availability", object] = values.unset, @@ -375,7 +578,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 OperatorPage(self._version, response) async def page_async( @@ -408,11 +617,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 OperatorPage(self._version, response) + def page_with_http_info( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorPage, status code, and headers + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = OperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with OperatorPage, status code, and headers + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = OperatorPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> OperatorPage: """ Retrieve a specific page of OperatorInstance records from the API. diff --git a/twilio/rest/intelligence/v2/operator_attachment.py b/twilio/rest/intelligence/v2/operator_attachment.py index 4ab8b48c10..d05769e12e 100644 --- a/twilio/rest/intelligence/v2/operator_attachment.py +++ b/twilio/rest/intelligence/v2/operator_attachment.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( "service_sid": service_sid or self.service_sid, "operator_sid": operator_sid or self.operator_sid, } + self._context: Optional[OperatorAttachmentContext] = None @property @@ -80,6 +82,24 @@ async def create_async(self) -> "OperatorAttachmentInstance": """ return await self._proxy.create_async() + def create_with_http_info(self) -> ApiResponse: + """ + Create the OperatorAttachmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info() + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the OperatorAttachmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async() + def delete(self) -> bool: """ Deletes the OperatorAttachmentInstance @@ -98,6 +118,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OperatorAttachmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OperatorAttachmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -129,6 +167,23 @@ def __init__(self, version: Version, service_sid: str, operator_sid: str): **self._solution ) + def _create(self) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create(self) -> OperatorAttachmentInstance: """ Create the OperatorAttachmentInstance @@ -136,16 +191,46 @@ def create(self) -> OperatorAttachmentInstance: :returns: The created OperatorAttachmentInstance """ - data = values.of({}) + payload, _, _ = self._create() + return OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the OperatorAttachmentInstance and return response metadata - payload = self._version.create(method="POST", uri=self._uri, data=data) - return OperatorAttachmentInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = OperatorAttachmentInstance( self._version, payload, service_sid=self._solution["service_sid"], operator_sid=self._solution["operator_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) async def create_async(self) -> OperatorAttachmentInstance: """ @@ -154,18 +239,43 @@ async def create_async(self) -> OperatorAttachmentInstance: :returns: The created OperatorAttachmentInstance """ - data = values.of({}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data + payload, _, _ = await self._create_async() + return OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], ) - return OperatorAttachmentInstance( + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the OperatorAttachmentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = OperatorAttachmentInstance( self._version, payload, service_sid=self._solution["service_sid"], operator_sid=self._solution["operator_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) def delete(self) -> bool: """ @@ -174,9 +284,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 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: @@ -186,10 +318,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 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: """ diff --git a/twilio/rest/intelligence/v2/operator_attachments.py b/twilio/rest/intelligence/v2/operator_attachments.py index 2500ef7224..0bfbacdcf7 100644 --- a/twilio/rest/intelligence/v2/operator_attachments.py +++ b/twilio/rest/intelligence/v2/operator_attachments.py @@ -13,6 +13,8 @@ """ 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 @@ -41,6 +43,7 @@ def __init__( self._solution = { "service_sid": service_sid or self.service_sid, } + self._context: Optional[OperatorAttachmentsContext] = None @property @@ -76,6 +79,24 @@ async def fetch_async(self) -> "OperatorAttachmentsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorAttachmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorAttachmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -103,6 +124,22 @@ def __init__(self, version: Version, service_sid: str): } 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 @@ -110,17 +147,43 @@ def fetch(self) -> OperatorAttachmentsInstance: :returns: The fetched OperatorAttachmentsInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return OperatorAttachmentsInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], ) - return OperatorAttachmentsInstance( + 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: """ @@ -129,17 +192,27 @@ async def fetch_async(self) -> OperatorAttachmentsInstance: :returns: The fetched OperatorAttachmentsInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return OperatorAttachmentsInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], ) - return OperatorAttachmentsInstance( + 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: """ diff --git a/twilio/rest/intelligence/v2/operator_type.py b/twilio/rest/intelligence/v2/operator_type.py index 9884df0aee..288595ad02 100644 --- a/twilio/rest/intelligence/v2/operator_type.py +++ b/twilio/rest/intelligence/v2/operator_type.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -27,14 +28,16 @@ class OperatorTypeInstance(InstanceResource): class Availability(object): INTERNAL = "internal" BETA = "beta" - PUBLIC = "public" + 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" @@ -93,6 +96,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[OperatorTypeContext] = None @property @@ -128,6 +132,24 @@ async def fetch_async(self) -> "OperatorTypeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -145,7 +167,7 @@ def __init__(self, version: Version, sid: str): Initialize the OperatorTypeContext :param version: Version that contains the resource - :param sid: A 34 character string that uniquely identifies this Operator Type. + :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) @@ -155,6 +177,22 @@ def __init__(self, version: Version, sid: str): } 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 @@ -162,17 +200,43 @@ def fetch(self) -> OperatorTypeInstance: :returns: The fetched OperatorTypeInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return OperatorTypeInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return OperatorTypeInstance( + 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: """ @@ -181,17 +245,27 @@ async def fetch_async(self) -> OperatorTypeInstance: :returns: The fetched OperatorTypeInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return OperatorTypeInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return OperatorTypeInstance( + 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: """ @@ -211,6 +285,7 @@ def get_instance(self, payload: Dict[str, Any]) -> OperatorTypeInstance: :param payload: Payload response from the API """ + return OperatorTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -237,6 +312,7 @@ def __init__(self, version: Version): def stream( self, + language_code: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> Iterator[OperatorTypeInstance]: @@ -246,6 +322,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. + :param str language_code: Returns Operator Types that support the provided language code. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -256,12 +333,13 @@ def stream( :returns: Generator that will yield up to limit results """ limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) + page = self.page(language_code=language_code, page_size=limits["page_size"]) return self._version.stream(page, limits["limit"]) async def stream_async( self, + language_code: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> AsyncIterator[OperatorTypeInstance]: @@ -271,6 +349,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. + :param str language_code: Returns Operator Types that support the provided language code. :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -281,12 +360,71 @@ async def stream_async( :returns: Generator that will yield up to limit results """ limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) + page = await self.page_async( + language_code=language_code, page_size=limits["page_size"] + ) return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OperatorTypeInstance and returns headers from first page + + + :param str language_code: Returns Operator Types that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + language_code=language_code, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OperatorTypeInstance and returns headers from first page + + + :param str language_code: Returns Operator Types that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + language_code=language_code, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, + language_code: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[OperatorTypeInstance]: @@ -295,6 +433,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. + :param str language_code: Returns Operator Types that support the provided language code. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -304,8 +443,10 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( + language_code=language_code, limit=limit, page_size=page_size, ) @@ -313,6 +454,7 @@ def list( async def list_async( self, + language_code: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[OperatorTypeInstance]: @@ -321,6 +463,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. + :param str language_code: Returns Operator Types that support the provided language code. :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -330,16 +473,75 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( + language_code=language_code, limit=limit, page_size=page_size, ) ] + def list_with_http_info( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OperatorTypeInstance and returns headers from first page + + + :param str language_code: Returns Operator Types that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OperatorTypeInstance and returns headers from first page + + + :param str language_code: Returns Operator Types that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, + language_code: Union[str, object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -348,6 +550,7 @@ def page( Retrieve a single page of OperatorTypeInstance records from the API. Request is executed immediately + :param language_code: Returns Operator Types that support the provided language code. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -356,17 +559,25 @@ def page( """ data = values.of( { + "LanguageCode": language_code, "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 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, @@ -375,6 +586,7 @@ async def page_async( Asynchronously retrieve a single page of OperatorTypeInstance records from the API. Request is executed immediately + :param language_code: Returns Operator Types that support the provided language code. :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -383,17 +595,98 @@ async def page_async( """ 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 + 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. @@ -422,7 +715,7 @@ def get(self, sid: str) -> OperatorTypeContext: """ Constructs a OperatorTypeContext - :param sid: A 34 character string that uniquely identifies this Operator Type. + :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) @@ -430,7 +723,7 @@ def __call__(self, sid: str) -> OperatorTypeContext: """ Constructs a OperatorTypeContext - :param sid: A 34 character string that uniquely identifies this Operator Type. + :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) diff --git a/twilio/rest/intelligence/v2/prebuilt_operator.py b/twilio/rest/intelligence/v2/prebuilt_operator.py index e00ceecac5..8dc5cdac4e 100644 --- a/twilio/rest/intelligence/v2/prebuilt_operator.py +++ b/twilio/rest/intelligence/v2/prebuilt_operator.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -29,6 +30,7 @@ class Availability(object): BETA = "beta" PUBLIC = "public" RETIRED = "retired" + GENERAL_AVAILABILITY = "general-availability" """ :ivar account_sid: The unique SID identifier of the Account the Pre-built Operator belongs to. @@ -72,6 +74,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PrebuiltOperatorContext] = None @property @@ -107,6 +110,24 @@ async def fetch_async(self) -> "PrebuiltOperatorInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PrebuiltOperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PrebuiltOperatorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -134,6 +155,22 @@ def __init__(self, version: Version, sid: str): } 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 @@ -141,17 +178,43 @@ def fetch(self) -> PrebuiltOperatorInstance: :returns: The fetched PrebuiltOperatorInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return PrebuiltOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return PrebuiltOperatorInstance( + 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: """ @@ -160,17 +223,27 @@ async def fetch_async(self) -> PrebuiltOperatorInstance: :returns: The fetched PrebuiltOperatorInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return PrebuiltOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return PrebuiltOperatorInstance( + 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: """ @@ -190,6 +263,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PrebuiltOperatorInstance: :param payload: Payload response from the API """ + return PrebuiltOperatorInstance(self._version, payload) def __repr__(self) -> str: @@ -284,6 +358,74 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PrebuiltOperatorInstance and returns headers from first page + + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PrebuiltOperatorInstance and returns headers from first page + + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, availability: Union[ @@ -309,6 +451,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( availability=availability, @@ -343,6 +486,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -353,6 +497,72 @@ async def list_async( ) ] + def list_with_http_info( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PrebuiltOperatorInstance and returns headers from first page + + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PrebuiltOperatorInstance and returns headers from first page + + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, availability: Union[ @@ -385,7 +595,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 PrebuiltOperatorPage(self._version, response) async def page_async( @@ -420,11 +636,101 @@ async def page_async( } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + response = await self._version.page_async( - method="GET", uri=self._uri, params=data + 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. diff --git a/twilio/rest/intelligence/v2/service.py b/twilio/rest/intelligence/v2/service.py index 8f5633d0fe..6a16c052fe 100644 --- a/twilio/rest/intelligence/v2/service.py +++ b/twilio/rest/intelligence/v2/service.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -46,6 +47,7 @@ class HttpMethod(object): :ivar webhook_http_method: :ivar read_only_attached_operator_sids: Operator sids attached to this service, read only :ivar version: The version number of this Service. + :ivar encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. """ def __init__( @@ -77,10 +79,14 @@ def __init__( "read_only_attached_operator_sids" ) self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.encryption_credential_sid: Optional[str] = payload.get( + "encryption_credential_sid" + ) self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -116,6 +122,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -134,6 +158,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -145,6 +187,7 @@ def update( media_redaction: Union[bool, object] = values.unset, webhook_url: Union[str, object] = values.unset, webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, ) -> "ServiceInstance": """ Update the ServiceInstance @@ -158,6 +201,7 @@ def update( :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. :param webhook_url: The URL Twilio will request when executing the Webhook. :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. :returns: The updated ServiceInstance """ @@ -171,6 +215,7 @@ def update( media_redaction=media_redaction, webhook_url=webhook_url, webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, ) async def update_async( @@ -184,6 +229,7 @@ async def update_async( media_redaction: Union[bool, object] = values.unset, webhook_url: Union[str, object] = values.unset, webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, ) -> "ServiceInstance": """ Asynchronous coroutine to update the ServiceInstance @@ -197,6 +243,7 @@ async def update_async( :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. :param webhook_url: The URL Twilio will request when executing the Webhook. :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. :returns: The updated ServiceInstance """ @@ -210,6 +257,91 @@ async def update_async( media_redaction=media_redaction, webhook_url=webhook_url, webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + unique_name=unique_name, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + unique_name=unique_name, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, ) def __repr__(self) -> str: @@ -239,6 +371,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Services/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ServiceInstance @@ -246,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 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: @@ -258,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 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: @@ -270,17 +462,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: """ @@ -289,19 +507,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, if_match: Union[str, object] = values.unset, auto_transcribe: Union[bool, object] = values.unset, @@ -312,22 +540,15 @@ def update( media_redaction: Union[bool, object] = values.unset, webhook_url: Union[str, object] = values.unset, webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, - ) -> ServiceInstance: + encryption_credential_sid: Union[str, object] = values.unset, + ) -> tuple: """ - Update the ServiceInstance - - :param if_match: The If-Match HTTP request header - :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. - :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. - :param friendly_name: A human readable description of this resource, up to 64 characters. - :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. - :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. - :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. - :param webhook_url: The URL Twilio will request when executing the Webhook. - :param webhook_http_method: + Internal helper for update operation - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "AutoTranscribe": serialize.boolean_to_string(auto_transcribe), @@ -338,21 +559,25 @@ def update( "MediaRedaction": serialize.boolean_to_string(media_redaction), "WebhookUrl": webhook_url, "WebhookHttpMethod": webhook_http_method, + "EncryptionCredentialSid": encryption_credential_sid, } ) - 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 ) - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, if_match: Union[str, object] = values.unset, auto_transcribe: Union[bool, object] = values.unset, @@ -363,9 +588,10 @@ async def update_async( media_redaction: Union[bool, object] = values.unset, webhook_url: Union[str, object] = values.unset, webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, ) -> ServiceInstance: """ - Asynchronous coroutine to update the ServiceInstance + Update the ServiceInstance :param if_match: The If-Match HTTP request header :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. @@ -376,101 +602,264 @@ async def update_async( :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. :param webhook_url: The URL Twilio will request when executing the Webhook. :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. :returns: The updated ServiceInstance """ - 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, - } - ) - headers = values.of( - { - "If-Match": if_match, - } - ) - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + 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 __repr__(self) -> str: - """ - 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( + def update_with_http_info( self, - unique_name: str, + 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, - language_code: 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, - ) -> ServiceInstance: + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Create the ServiceInstance + Update 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 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 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 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 created ServiceInstance + :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( @@ -484,17 +873,20 @@ def create( "MediaRedaction": serialize.boolean_to_string(media_redaction), "WebhookUrl": webhook_url, "WebhookHttpMethod": webhook_http_method, + "EncryptionCredentialSid": encryption_credential_sid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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 ServiceInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: str, auto_transcribe: Union[bool, object] = values.unset, @@ -505,9 +897,10 @@ async def create_async( media_redaction: Union[bool, object] = values.unset, webhook_url: Union[str, object] = values.unset, webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, ) -> ServiceInstance: """ - Asynchronously create the ServiceInstance + Create the ServiceInstance :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. @@ -518,9 +911,87 @@ async def create_async( :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. :param webhook_url: The URL Twilio will request when executing the Webhook. :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. :returns: The created ServiceInstance """ + payload, _, _ = self._create( + unique_name=unique_name, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + language_code=language_code, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: str, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param language_code: The language code set during Service creation determines the Transcription language for all call recordings processed by that Service. The default is en-US if no language code is set. A Service can only support one language code, and it cannot be updated once it's set. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + :param encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + language_code=language_code, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + encryption_credential_sid=encryption_credential_sid, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: str, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + encryption_credential_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -533,16 +1004,106 @@ async def create_async( "MediaRedaction": serialize.boolean_to_string(media_redaction), "WebhookUrl": webhook_url, "WebhookHttpMethod": webhook_http_method, + "EncryptionCredentialSid": encryption_credential_sid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, + 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, @@ -593,6 +1154,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -612,6 +1223,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -638,6 +1250,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -646,6 +1259,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ServiceInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -670,7 +1333,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( @@ -697,11 +1366,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/intelligence/v2/transcript/__init__.py b/twilio/rest/intelligence/v2/transcript/__init__.py index bc71542bc0..19284fa98d 100644 --- a/twilio/rest/intelligence/v2/transcript/__init__.py +++ b/twilio/rest/intelligence/v2/transcript/__init__.py @@ -15,11 +15,18 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from twilio.base.version import Version from twilio.base.page import Page +from twilio.rest.intelligence.v2.transcript.encrypted_operator_results import ( + EncryptedOperatorResultsList, +) +from twilio.rest.intelligence.v2.transcript.encrypted_sentences import ( + EncryptedSentencesList, +) from twilio.rest.intelligence.v2.transcript.media import MediaList from twilio.rest.intelligence.v2.transcript.operator_result import OperatorResultList from twilio.rest.intelligence.v2.transcript.sentence import SentenceList @@ -31,8 +38,10 @@ class Status(object): QUEUED = "queued" IN_PROGRESS = "in-progress" COMPLETED = "completed" + NEW = "new" FAILED = "failed" CANCELED = "canceled" + ERROR = "error" """ :ivar account_sid: The unique SID identifier of the Account. @@ -49,6 +58,7 @@ class Status(object): :ivar duration: The duration of this Transcript's source :ivar url: The URL of this resource. :ivar redaction: If the transcript has been redacted, a redacted alternative of the transcript will be available. + :ivar encryption_credential_sid: The unique SID identifier of the Public Key resource used to encrypt the sentences and operator results. :ivar links: """ @@ -77,11 +87,15 @@ def __init__( self.duration: Optional[int] = deserialize.integer(payload.get("duration")) self.url: Optional[str] = payload.get("url") self.redaction: Optional[bool] = payload.get("redaction") + self.encryption_credential_sid: Optional[str] = payload.get( + "encryption_credential_sid" + ) self.links: Optional[Dict[str, object]] = payload.get("links") self._solution = { "sid": sid or self.sid, } + self._context: Optional[TranscriptContext] = None @property @@ -117,6 +131,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TranscriptInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TranscriptInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TranscriptInstance": """ Fetch the TranscriptInstance @@ -135,6 +167,38 @@ async def fetch_async(self) -> "TranscriptInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TranscriptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + @property + def encrypted_operator_results(self) -> EncryptedOperatorResultsList: + """ + Access the encrypted_operator_results + """ + return self._proxy.encrypted_operator_results + + @property + def encrypted_sentences(self) -> EncryptedSentencesList: + """ + Access the encrypted_sentences + """ + return self._proxy.encrypted_sentences + @property def media(self) -> MediaList: """ @@ -183,10 +247,26 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Transcripts/{sid}".format(**self._solution) + self._encrypted_operator_results: Optional[EncryptedOperatorResultsList] = None + self._encrypted_sentences: Optional[EncryptedSentencesList] = None self._media: Optional[MediaList] = None self._operator_results: Optional[OperatorResultList] = None self._sentences: Optional[SentenceList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TranscriptInstance @@ -194,9 +274,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 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: @@ -206,9 +308,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 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: @@ -218,17 +344,43 @@ def fetch(self) -> TranscriptInstance: :returns: The fetched TranscriptInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return TranscriptInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return TranscriptInstance( + 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: """ @@ -237,17 +389,51 @@ async def fetch_async(self) -> TranscriptInstance: :returns: The fetched TranscriptInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return TranscriptInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return TranscriptInstance( + 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: @@ -303,6 +489,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TranscriptInstance: :param payload: Payload response from the API """ + return TranscriptInstance(self._version, payload) def __repr__(self) -> str: @@ -327,22 +514,18 @@ def __init__(self, version: Version): self._uri = "/Transcripts" - def create( + def _create( self, service_sid: str, channel: object, customer_key: Union[str, object] = values.unset, media_start_time: Union[datetime, object] = values.unset, - ) -> TranscriptInstance: + ) -> tuple: """ - Create the TranscriptInstance - - :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. + Internal helper for create operation - :returns: The created TranscriptInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -355,13 +538,15 @@ def create( ) headers = values.of({"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 TranscriptInstance(self._version, payload) - - async def create_async( + def create( self, service_sid: str, channel: object, @@ -369,7 +554,7 @@ async def create_async( media_start_time: Union[datetime, object] = values.unset, ) -> TranscriptInstance: """ - Asynchronously create the TranscriptInstance + Create the TranscriptInstance :param service_sid: The unique SID identifier of the Service. :param channel: JSON object describing Media Channel including Source and Participants @@ -378,6 +563,53 @@ async def create_async( :returns: The created TranscriptInstance """ + payload, _, _ = self._create( + service_sid=service_sid, + channel=channel, + customer_key=customer_key, + media_start_time=media_start_time, + ) + return TranscriptInstance(self._version, payload) + + def create_with_http_info( + self, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Create the TranscriptInstance and return response metadata + + :param service_sid: The unique SID identifier of the Service. + :param channel: JSON object describing Media Channel including Source and Participants + :param customer_key: Used to store client provided metadata. Maximum of 64 double-byte UTF8 characters. + :param media_start_time: The date that this Transcript's media was started, given in ISO 8601 format. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + service_sid=service_sid, + channel=channel, + customer_key=customer_key, + media_start_time=media_start_time, + ) + instance = TranscriptInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -389,12 +621,65 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -497,6 +782,106 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TranscriptInstance and returns headers from first page + + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TranscriptInstance and returns headers from first page + + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, service_sid: Union[str, object] = values.unset, @@ -532,6 +917,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( service_sid=service_sid, @@ -582,6 +968,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -598,6 +985,104 @@ async def list_async( ) ] + def list_with_http_info( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TranscriptInstance and returns headers from first page + + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TranscriptInstance and returns headers from first page + + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, service_sid: Union[str, object] = values.unset, @@ -646,7 +1131,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 TranscriptPage(self._version, response) async def page_async( @@ -697,11 +1188,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 TranscriptPage(self._version, response) + def page_with_http_info( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param service_sid: The unique SID identifier of the Service. + :param before_start_time: Filter by before StartTime. + :param after_start_time: Filter by after StartTime. + :param before_date_created: Filter by before DateCreated. + :param after_date_created: Filter by after DateCreated. + :param status: Filter by status. + :param language_code: Filter by Language Code. + :param source_sid: Filter by SourceSid. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptPage, status code, and headers + """ + data = values.of( + { + "ServiceSid": service_sid, + "BeforeStartTime": before_start_time, + "AfterStartTime": after_start_time, + "BeforeDateCreated": before_date_created, + "AfterDateCreated": after_date_created, + "Status": status, + "LanguageCode": language_code, + "SourceSid": source_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TranscriptPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param service_sid: The unique SID identifier of the Service. + :param before_start_time: Filter by before StartTime. + :param after_start_time: Filter by after StartTime. + :param before_date_created: Filter by before DateCreated. + :param after_date_created: Filter by after DateCreated. + :param status: Filter by status. + :param language_code: Filter by Language Code. + :param source_sid: Filter by SourceSid. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TranscriptPage, status code, and headers + """ + data = values.of( + { + "ServiceSid": service_sid, + "BeforeStartTime": before_start_time, + "AfterStartTime": after_start_time, + "BeforeDateCreated": before_date_created, + "AfterDateCreated": after_date_created, + "Status": status, + "LanguageCode": language_code, + "SourceSid": source_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TranscriptPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> TranscriptPage: """ Retrieve a specific page of TranscriptInstance records from the API. diff --git a/twilio/rest/intelligence/v2/transcript/encrypted_operator_results.py b/twilio/rest/intelligence/v2/transcript/encrypted_operator_results.py new file mode 100644 index 0000000000..4262a2ce09 --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/encrypted_operator_results.py @@ -0,0 +1,313 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class EncryptedOperatorResultsInstance(InstanceResource): + """ + :ivar locations: The locations of the encrypted operator results. + :ivar transcript_sid: + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], transcript_sid: str): + super().__init__(version) + + self.locations: Optional[List[str]] = payload.get("locations") + self.transcript_sid: Optional[str] = payload.get("transcript_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "transcript_sid": transcript_sid, + } + + self._context: Optional[EncryptedOperatorResultsContext] = None + + @property + def _proxy(self) -> "EncryptedOperatorResultsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EncryptedOperatorResultsContext for this EncryptedOperatorResultsInstance + """ + if self._context is None: + self._context = EncryptedOperatorResultsContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + ) + return self._context + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> "EncryptedOperatorResultsInstance": + """ + Fetch the EncryptedOperatorResultsInstance + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: The fetched EncryptedOperatorResultsInstance + """ + return self._proxy.fetch( + redacted=redacted, + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> "EncryptedOperatorResultsInstance": + """ + Asynchronous coroutine to fetch the EncryptedOperatorResultsInstance + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: The fetched EncryptedOperatorResultsInstance + """ + return await self._proxy.fetch_async( + redacted=redacted, + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the EncryptedOperatorResultsInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + redacted=redacted, + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EncryptedOperatorResultsInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + redacted=redacted, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class EncryptedOperatorResultsContext(InstanceContext): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the EncryptedOperatorResultsContext + + :param version: Version that contains the resource + :param transcript_sid: The unique SID identifier of the Transcript. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + } + self._uri = "/Transcripts/{transcript_sid}/OperatorResults/Encrypted".format( + **self._solution + ) + + def _fetch(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> EncryptedOperatorResultsInstance: + """ + Fetch the EncryptedOperatorResultsInstance + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: The fetched EncryptedOperatorResultsInstance + """ + payload, _, _ = self._fetch(redacted=redacted) + return EncryptedOperatorResultsInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the EncryptedOperatorResultsInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(redacted=redacted) + instance = EncryptedOperatorResultsInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> EncryptedOperatorResultsInstance: + """ + Asynchronous coroutine to fetch the EncryptedOperatorResultsInstance + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: The fetched EncryptedOperatorResultsInstance + """ + payload, _, _ = await self._fetch_async(redacted=redacted) + return EncryptedOperatorResultsInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EncryptedOperatorResultsInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Operator Results. If redaction is enabled, the default is `true` to access redacted operator results. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(redacted=redacted) + instance = EncryptedOperatorResultsInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class EncryptedOperatorResultsList(ListResource): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the EncryptedOperatorResultsList + + :param version: Version that contains the resource + :param transcript_sid: The unique SID identifier of the Transcript. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + } + + def get(self) -> EncryptedOperatorResultsContext: + """ + Constructs a EncryptedOperatorResultsContext + + """ + return EncryptedOperatorResultsContext( + self._version, transcript_sid=self._solution["transcript_sid"] + ) + + def __call__(self) -> EncryptedOperatorResultsContext: + """ + Constructs a EncryptedOperatorResultsContext + + """ + return EncryptedOperatorResultsContext( + self._version, transcript_sid=self._solution["transcript_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/transcript/encrypted_sentences.py b/twilio/rest/intelligence/v2/transcript/encrypted_sentences.py new file mode 100644 index 0000000000..ed2406926e --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/encrypted_sentences.py @@ -0,0 +1,309 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class EncryptedSentencesInstance(InstanceResource): + """ + :ivar location: The location of the encrypted sentences. + :ivar transcript_sid: + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], transcript_sid: str): + super().__init__(version) + + self.location: Optional[str] = payload.get("location") + self.transcript_sid: Optional[str] = payload.get("transcript_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "transcript_sid": transcript_sid, + } + + self._context: Optional[EncryptedSentencesContext] = None + + @property + def _proxy(self) -> "EncryptedSentencesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EncryptedSentencesContext for this EncryptedSentencesInstance + """ + if self._context is None: + self._context = EncryptedSentencesContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + ) + return self._context + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> "EncryptedSentencesInstance": + """ + Fetch the EncryptedSentencesInstance + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: The fetched EncryptedSentencesInstance + """ + return self._proxy.fetch( + redacted=redacted, + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> "EncryptedSentencesInstance": + """ + Asynchronous coroutine to fetch the EncryptedSentencesInstance + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: The fetched EncryptedSentencesInstance + """ + return await self._proxy.fetch_async( + redacted=redacted, + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the EncryptedSentencesInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + redacted=redacted, + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EncryptedSentencesInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + redacted=redacted, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EncryptedSentencesContext(InstanceContext): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the EncryptedSentencesContext + + :param version: Version that contains the resource + :param transcript_sid: The unique SID identifier of the Transcript. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + } + self._uri = "/Transcripts/{transcript_sid}/Sentences/Encrypted".format( + **self._solution + ) + + def _fetch(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, params=params, headers=headers + ) + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> EncryptedSentencesInstance: + """ + Fetch the EncryptedSentencesInstance + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: The fetched EncryptedSentencesInstance + """ + payload, _, _ = self._fetch(redacted=redacted) + return EncryptedSentencesInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the EncryptedSentencesInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(redacted=redacted) + instance = EncryptedSentencesInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, params=params, headers=headers + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> EncryptedSentencesInstance: + """ + Asynchronous coroutine to fetch the EncryptedSentencesInstance + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: The fetched EncryptedSentencesInstance + """ + payload, _, _ = await self._fetch_async(redacted=redacted) + return EncryptedSentencesInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EncryptedSentencesInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(redacted=redacted) + instance = EncryptedSentencesInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class EncryptedSentencesList(ListResource): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the EncryptedSentencesList + + :param version: Version that contains the resource + :param transcript_sid: The unique SID identifier of the Transcript. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + } + + def get(self) -> EncryptedSentencesContext: + """ + Constructs a EncryptedSentencesContext + + """ + return EncryptedSentencesContext( + self._version, transcript_sid=self._solution["transcript_sid"] + ) + + def __call__(self) -> EncryptedSentencesContext: + """ + Constructs a EncryptedSentencesContext + + """ + return EncryptedSentencesContext( + self._version, transcript_sid=self._solution["transcript_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/transcript/media.py b/twilio/rest/intelligence/v2/transcript/media.py index 74d3ab9959..a4d08a488d 100644 --- a/twilio/rest/intelligence/v2/transcript/media.py +++ b/twilio/rest/intelligence/v2/transcript/media.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -41,6 +42,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], sid: str): self._solution = { "sid": sid, } + self._context: Optional[MediaContext] = None @property @@ -84,6 +86,34 @@ async def fetch_async( redacted=redacted, ) + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the MediaInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + redacted=redacted, + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MediaInstance with HTTP info + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + redacted=redacted, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -111,56 +141,118 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Transcripts/{sid}/Media".format(**self._solution) - def fetch(self, redacted: Union[bool, object] = values.unset) -> MediaInstance: + def _fetch(self, redacted: Union[bool, object] = values.unset) -> tuple: """ - Fetch the MediaInstance - - :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + Internal helper for fetch operation - :returns: The fetched MediaInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Redacted": serialize.boolean_to_string(redacted), } ) - 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, redacted: Union[bool, object] = values.unset) -> MediaInstance: + """ + Fetch the MediaInstance + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: The fetched MediaInstance + """ + payload, _, _ = self._fetch(redacted=redacted) return MediaInstance( self._version, payload, sid=self._solution["sid"], ) - async def fetch_async( + def fetch_with_http_info( self, redacted: Union[bool, object] = values.unset - ) -> MediaInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the MediaInstance + Fetch the MediaInstance and return response metadata :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. - :returns: The fetched MediaInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(redacted=redacted) + instance = MediaInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Redacted": serialize.boolean_to_string(redacted), } ) - 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, redacted: Union[bool, object] = values.unset + ) -> MediaInstance: + """ + Asynchronous coroutine to fetch the MediaInstance + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: The fetched MediaInstance + """ + payload, _, _ = await self._fetch_async(redacted=redacted) return MediaInstance( self._version, payload, sid=self._solution["sid"], ) + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MediaInstance and return response metadata + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(redacted=redacted) + instance = MediaInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/intelligence/v2/transcript/operator_result.py b/twilio/rest/intelligence/v2/transcript/operator_result.py index 9d1d614f4d..01af814a79 100644 --- a/twilio/rest/intelligence/v2/transcript/operator_result.py +++ b/twilio/rest/intelligence/v2/transcript/operator_result.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,11 +25,13 @@ class OperatorResultInstance(InstanceResource): class OperatorType(object): - CONVERSATION_CLASSIFY = "conversation_classify" - UTTERANCE_CLASSIFY = "utterance_classify" + CONVERSATION_CLASSIFY = "conversation-classify" + UTTERANCE_CLASSIFY = "utterance-classify" EXTRACT = "extract" - EXTRACT_NORMALIZE = "extract_normalize" - PII_EXTRACT = "pii_extract" + EXTRACT_NORMALIZE = "extract-normalize" + PII_EXTRACT = "pii-extract" + TEXT_GENERATION = "text-generation" + JSON = "json" """ :ivar operator_type: @@ -44,6 +47,7 @@ class OperatorType(object): :ivar label_probabilities: The labels probabilities. This might be available on conversation classify model outputs. :ivar extract_results: List of text extraction results. This might be available on classify-extract model outputs. :ivar text_generation_results: Output of a text generation operator for example Conversation Sumamary. + :ivar json_results: :ivar transcript_sid: A 34 character string that uniquely identifies this Transcript. :ivar url: The URL of this resource. """ @@ -84,6 +88,7 @@ def __init__( self.text_generation_results: Optional[Dict[str, object]] = payload.get( "text_generation_results" ) + self.json_results: Optional[Dict[str, object]] = payload.get("json_results") self.transcript_sid: Optional[str] = payload.get("transcript_sid") self.url: Optional[str] = payload.get("url") @@ -91,6 +96,7 @@ def __init__( "transcript_sid": transcript_sid, "operator_sid": operator_sid or self.operator_sid, } + self._context: Optional[OperatorResultContext] = None @property @@ -137,6 +143,34 @@ async def fetch_async( redacted=redacted, ) + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the OperatorResultInstance with HTTP info + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + redacted=redacted, + ) + + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorResultInstance with HTTP info + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + redacted=redacted, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -170,25 +204,39 @@ def __init__(self, version: Version, transcript_sid: str, operator_sid: str): ) ) - def fetch( - self, redacted: Union[bool, object] = values.unset - ) -> OperatorResultInstance: + def _fetch(self, redacted: Union[bool, object] = values.unset) -> tuple: """ - Fetch the OperatorResultInstance - - :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + Internal helper for fetch operation - :returns: The fetched OperatorResultInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Redacted": serialize.boolean_to_string(redacted), } ) - 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, 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, @@ -196,27 +244,58 @@ def fetch( operator_sid=self._solution["operator_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, redacted: Union[bool, object] = values.unset - ) -> OperatorResultInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the OperatorResultInstance + Fetch the OperatorResultInstance and return response metadata :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. - :returns: The fetched OperatorResultInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch(redacted=redacted) + instance = OperatorResultInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async(self, redacted: Union[bool, object] = values.unset) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Redacted": serialize.boolean_to_string(redacted), } ) - 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, 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, @@ -224,6 +303,25 @@ async def fetch_async( operator_sid=self._solution["operator_sid"], ) + async def fetch_with_http_info_async( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OperatorResultInstance and return response metadata + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async(redacted=redacted) + instance = OperatorResultInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -242,6 +340,7 @@ def get_instance(self, payload: Dict[str, Any]) -> OperatorResultInstance: :param payload: Payload response from the API """ + return OperatorResultInstance( self._version, payload, transcript_sid=self._solution["transcript_sid"] ) @@ -329,6 +428,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams OperatorResultInstance and returns headers from first page + + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + redacted=redacted, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams OperatorResultInstance and returns headers from first page + + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + redacted=redacted, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, redacted: Union[bool, object] = values.unset, @@ -350,6 +505,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( redacted=redacted, @@ -379,6 +535,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -388,6 +545,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists OperatorResultInstance and returns headers from first page + + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + redacted=redacted, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists OperatorResultInstance and returns headers from first page + + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + redacted=redacted, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, redacted: Union[bool, object] = values.unset, @@ -415,8 +628,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return OperatorResultPage(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 OperatorResultPage(self._version, response, solution=self._solution) async def page_async( self, @@ -445,10 +664,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 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 + ) ) - return OperatorResultPage(self._version, response, self._solution) + 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: """ @@ -460,7 +759,7 @@ def get_page(self, target_url: str) -> OperatorResultPage: :returns: Page of OperatorResultInstance """ response = self._version.domain.twilio.request("GET", target_url) - return OperatorResultPage(self._version, response, self._solution) + return OperatorResultPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> OperatorResultPage: """ @@ -472,7 +771,7 @@ async def get_page_async(self, target_url: str) -> OperatorResultPage: :returns: Page of OperatorResultInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return OperatorResultPage(self._version, response, self._solution) + return OperatorResultPage(self._version, response, solution=self._solution) def get(self, operator_sid: str) -> OperatorResultContext: """ diff --git a/twilio/rest/intelligence/v2/transcript/sentence.py b/twilio/rest/intelligence/v2/transcript/sentence.py index 5bdd18b00f..ee11548693 100644 --- a/twilio/rest/intelligence/v2/transcript/sentence.py +++ b/twilio/rest/intelligence/v2/transcript/sentence.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -30,6 +31,7 @@ class SentenceInstance(InstanceResource): :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): @@ -41,15 +43,12 @@ def __init__(self, version: Version, payload: Dict[str, Any], transcript_sid: st self.sentence_index: Optional[int] = deserialize.integer( payload.get("sentence_index") ) - self.start_time: Optional[float] = deserialize.decimal( - payload.get("start_time") - ) - self.end_time: Optional[float] = deserialize.decimal(payload.get("end_time")) + self.start_time: Optional[str] = payload.get("start_time") + self.end_time: Optional[str] = payload.get("end_time") self.transcript: Optional[str] = payload.get("transcript") self.sid: Optional[str] = payload.get("sid") - self.confidence: Optional[float] = deserialize.decimal( - payload.get("confidence") - ) + self.confidence: Optional[str] = payload.get("confidence") + self.words: Optional[List[Dict[str, object]]] = payload.get("words") self._solution = { "transcript_sid": transcript_sid, @@ -73,6 +72,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SentenceInstance: :param payload: Payload response from the API """ + return SentenceInstance( self._version, payload, transcript_sid=self._solution["transcript_sid"] ) @@ -107,6 +107,7 @@ def __init__(self, version: Version, transcript_sid: str): 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]: @@ -117,6 +118,7 @@ def stream( 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 @@ -127,13 +129,18 @@ def stream( :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"]) + 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]: @@ -144,6 +151,7 @@ async def stream_async( 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 @@ -154,13 +162,82 @@ 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(redacted=redacted, page_size=limits["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]: @@ -170,6 +247,7 @@ def list( 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 @@ -179,9 +257,11 @@ def list( :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, ) @@ -190,6 +270,7 @@ def list( 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]: @@ -199,6 +280,7 @@ async def list_async( 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 @@ -208,18 +290,83 @@ async def list_async( :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, @@ -229,6 +376,7 @@ def page( 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 @@ -238,18 +386,26 @@ def page( 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, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SentencePage(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 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, @@ -259,6 +415,7 @@ async def page_async( 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 @@ -268,16 +425,103 @@ async def page_async( 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 + 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 + ) ) - return SentencePage(self._version, response, self._solution) + 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: """ @@ -289,7 +533,7 @@ def get_page(self, target_url: str) -> SentencePage: :returns: Page of SentenceInstance """ response = self._version.domain.twilio.request("GET", target_url) - return SentencePage(self._version, response, self._solution) + return SentencePage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> SentencePage: """ @@ -301,7 +545,7 @@ async def get_page_async(self, target_url: str) -> SentencePage: :returns: Page of SentenceInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return SentencePage(self._version, response, self._solution) + return SentencePage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/intelligence/v3/__init__.py b/twilio/rest/intelligence/v3/__init__.py new file mode 100644 index 0000000000..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/v1/credential.py b/twilio/rest/ip_messaging/v1/credential.py index 279aef7860..b363627051 100644 --- a/twilio/rest/ip_messaging/v1/credential.py +++ b/twilio/rest/ip_messaging/v1/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -174,6 +212,66 @@ async def update_async( secret=secret, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,6 +299,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -208,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: @@ -220,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: @@ -232,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: """ @@ -251,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, @@ -284,6 +514,64 @@ 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, @@ -294,14 +582,15 @@ def update( "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, @@ -324,24 +613,47 @@ async def update_async( :returns: The updated CredentialInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": serialize.boolean_to_string(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: """ @@ -361,6 +673,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: :param payload: Payload response from the API """ + return CredentialInstance(self._version, payload) def __repr__(self) -> str: @@ -385,7 +698,7 @@ def __init__(self, version: Version): self._uri = "/Credentials" - def create( + def _create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -394,19 +707,12 @@ def create( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Create the CredentialInstance + Internal helper for create operation - :param type: - :param friendly_name: - :param certificate: - :param private_key: - :param sandbox: - :param api_key: - :param secret: - - :returns: The created CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -422,13 +728,15 @@ def create( ) headers = values.of({"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 CredentialInstance(self._version, payload) - - async def create_async( + def create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -439,7 +747,7 @@ async def create_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronously create the CredentialInstance + Create the CredentialInstance :param type: :param friendly_name: @@ -451,6 +759,68 @@ async def create_async( :returns: The created CredentialInstance """ + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -465,12 +835,83 @@ async def create_async( ) headers = values.of({"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, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance + """ + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload) + async def create_with_http_info_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -521,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, @@ -540,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -566,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( @@ -574,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, @@ -598,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( @@ -625,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 e0b52e2738..61c06df216 100644 --- a/twilio/rest/ip_messaging/v1/service/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -94,6 +95,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -129,6 +131,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -147,6 +167,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -495,121 +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, @@ -665,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: @@ -724,86 +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": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": serialize.boolean_to_string( - notifications_new_message_enabled - ), - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( - notifications_added_to_channel_enabled - ), - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( - notifications_removed_from_channel_enabled - ), - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( - notifications_invited_to_channel_enabled - ), - "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "WebhookMethod": webhook_method, - "WebhookFilters": serialize.map(webhook_filters, lambda e: e), - "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, - "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, - "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, - "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, - "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, - "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, - "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, - "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, - "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, - "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, - "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, - "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, - "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, - "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, - "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, - "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, - "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, - "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, - "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, - "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, - "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, - "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, - "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, - "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, - "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, - "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, - "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, - "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, - "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, - "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, - "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, - "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, - "Limits.ChannelMembers": limits_channel_members, - "Limits.UserChannels": limits_user_channels, - } - ) - - payload = 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, @@ -859,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: @@ -918,8 +822,832 @@ async def update_async( :param limits_channel_members: :param limits_user_channels: - :returns: The updated ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers + ) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _fetch(self) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + payload, _, _ = self._update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "FriendlyName": friendly_name, @@ -988,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: @@ -1051,6 +2131,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -1075,13 +2156,12 @@ def __init__(self, version: Version): self._uri = "/Services" - def create(self, friendly_name: str) -> ServiceInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the ServiceInstance + Internal helper for create operation - :param friendly_name: - - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -1091,19 +2171,43 @@ def create(self, friendly_name: str) -> ServiceInstance: ) headers = values.of({"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, 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( @@ -1113,12 +2217,39 @@ async def create_async(self, friendly_name: str) -> ServiceInstance: ) headers = values.of({"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, 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, @@ -1169,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, @@ -1188,6 +2369,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -1214,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( @@ -1222,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, @@ -1246,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( @@ -1273,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 57d2d245ec..bca3bc717b 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/channel/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[ChannelContext] = None @property @@ -120,6 +122,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ChannelInstance": """ Fetch the ChannelInstance @@ -138,6 +158,24 @@ async def fetch_async(self) -> "ChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -180,6 +218,48 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance with HTTP info + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + @property def invites(self) -> InviteList: """ @@ -234,6 +314,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._members: Optional[MemberList] = None self._messages: Optional[MessageList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ChannelInstance @@ -241,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: @@ -253,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: @@ -265,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: """ @@ -285,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 + Internal helper for update operation - :param friendly_name: - :param unique_name: - :param attributes: - - :returns: The updated ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -320,13 +496,34 @@ def update( "Attributes": attributes, } ) + 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, + 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, @@ -334,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, @@ -356,13 +577,34 @@ async def update_async( "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, + 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, @@ -370,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: """ @@ -427,6 +695,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: :param payload: Payload response from the API """ + return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -458,22 +727,18 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Channels".format(**self._solution) - def create( + def _create( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, type: Union["ChannelInstance.ChannelType", object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Create the ChannelInstance + Internal helper for create operation - :param friendly_name: - :param unique_name: - :param attributes: - :param type: - - :returns: The created ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -486,30 +751,81 @@ def create( ) headers = values.of({"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, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: The created ChannelInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, type: Union["ChannelInstance.ChannelType", object] = values.unset, - ) -> ChannelInstance: + ) -> ApiResponse: """ - Asynchronously create the ChannelInstance + Create the ChannelInstance and return response metadata :param friendly_name: :param unique_name: :param attributes: :param type: - :returns: The created ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -522,14 +838,69 @@ async def create_async( ) headers = values.of({"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, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: The created ChannelInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ChannelInstance and return response metadata + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, @@ -584,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, @@ -605,6 +1032,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -634,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( @@ -643,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, @@ -670,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, @@ -700,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: """ @@ -715,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: """ @@ -727,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 f4c3476edb..f0b7e70c47 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/invite.py +++ b/twilio/rest/ip_messaging/v1/service/channel/invite.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InviteContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InviteInstance": """ Fetch the InviteInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "InviteInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,6 +194,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InviteInstance @@ -163,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: @@ -175,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: @@ -187,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: """ @@ -208,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: """ @@ -240,6 +378,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: :param payload: Payload response from the API """ + return InviteInstance( self._version, payload, @@ -278,16 +417,14 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> tuple: """ - Create the InviteInstance - - :param identity: - :param role_sid: + Internal helper for create operation - :returns: The created InviteInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -298,10 +435,26 @@ def create( ) headers = values.of({"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, 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, @@ -309,16 +462,36 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> ApiResponse: """ - Asynchronously create the InviteInstance + Create the InviteInstance and return response metadata :param identity: :param role_sid: - :returns: The created InviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -329,10 +502,26 @@ async def create_async( ) headers = values.of({"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, 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, @@ -340,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, @@ -394,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, @@ -415,6 +682,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -444,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( @@ -453,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, @@ -480,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, @@ -510,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: """ @@ -525,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: """ @@ -537,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 4452699ceb..6dccde7822 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/member.py +++ b/twilio/rest/ip_messaging/v1/service/channel/member.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MemberContext] = None @property @@ -109,6 +111,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MemberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MemberInstance": """ Fetch the MemberInstance @@ -127,6 +147,24 @@ async def fetch_async(self) -> "MemberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, role_sid: Union[str, object] = values.unset, @@ -163,6 +201,42 @@ async def update_async( last_consumed_message_index=last_consumed_message_index, ) + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP info + + :param role_sid: + :param last_consumed_message_index: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance with HTTP info + + :param role_sid: + :param last_consumed_message_index: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -198,6 +272,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MemberInstance @@ -205,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: @@ -217,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: @@ -229,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: """ @@ -250,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, @@ -298,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" - 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, + 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, @@ -332,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 @@ -350,6 +610,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -388,16 +649,14 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> MemberInstance: + ) -> tuple: """ - Create the MemberInstance - - :param identity: - :param role_sid: + Internal helper for create operation - :returns: The created MemberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -408,10 +667,26 @@ def create( ) headers = values.of({"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, 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, @@ -419,16 +694,36 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> MemberInstance: + ) -> ApiResponse: """ - Asynchronously create the MemberInstance + Create the MemberInstance and return response metadata :param identity: :param role_sid: - :returns: The created MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -439,10 +734,26 @@ async def create_async( ) headers = values.of({"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, 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, @@ -450,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, @@ -504,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, @@ -525,6 +914,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -554,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( @@ -563,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, @@ -590,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, @@ -620,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: """ @@ -635,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: """ @@ -647,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 5d3f2eb577..6d0ba2da88 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/message.py +++ b/twilio/rest/ip_messaging/v1/service/channel/message.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -114,6 +116,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -132,6 +152,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, body: Union[str, object] = values.unset, @@ -168,6 +206,42 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param body: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + body=body, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :param body: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + body=body, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -203,6 +277,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MessageInstance @@ -210,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: @@ -222,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: @@ -234,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: """ @@ -255,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 - - :param body: - :param attributes: + Internal helper for update operation - :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, @@ -303,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({}) + + 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, + 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, @@ -337,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 @@ -355,6 +609,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, @@ -393,20 +648,17 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, body: str, from_: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance + Internal helper for create operation - :param body: - :param from_: - :param attributes: - - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -418,10 +670,30 @@ def create( ) headers = values.of({"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, + 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, @@ -429,20 +701,43 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, body: str, from_: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> ApiResponse: """ - Asynchronously create the MessageInstance + Create the MessageInstance and return response metadata :param body: :param from_: :param attributes: - :returns: The created MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + body=body, from_=from_, attributes=attributes + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -454,10 +749,32 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -465,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, @@ -519,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, @@ -540,6 +939,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -569,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( @@ -578,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, @@ -605,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, @@ -635,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: """ @@ -650,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: """ @@ -662,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 5f5b19cfe9..e7156129ef 100644 --- a/twilio/rest/ip_messaging/v1/service/role.py +++ b/twilio/rest/ip_messaging/v1/service/role.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[RoleContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoleInstance": """ Fetch the RoleInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "RoleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, permission: List[str]) -> "RoleInstance": """ Update the RoleInstance @@ -145,6 +183,30 @@ async def update_async(self, permission: List[str]) -> "RoleInstance": permission=permission, ) + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + permission=permission, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -174,6 +236,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoleInstance @@ -181,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: @@ -193,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: @@ -205,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: """ @@ -225,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, @@ -238,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({}) + + 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, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + payload, _, _ = self._update(permission=permission) return RoleInstance( self._version, payload, @@ -265,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, @@ -292,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 @@ -310,6 +528,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -341,17 +560,14 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Roles".format(**self._solution) - def create( + def _create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> tuple: """ - Create the RoleInstance + Internal helper for create operation - :param friendly_name: - :param type: - :param permission: - - :returns: The created RoleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -363,25 +579,61 @@ def create( ) headers = values.of({"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, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> ApiResponse: """ - Asynchronously create the RoleInstance + Create the RoleInstance and return response metadata :param friendly_name: :param type: :param permission: - :returns: The created RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -393,14 +645,53 @@ async def create_async( ) headers = values.of({"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, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :param friendly_name: + :param type: + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -451,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, @@ -470,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -496,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( @@ -504,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, @@ -528,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, @@ -555,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: """ @@ -570,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: """ @@ -582,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 91364d8f96..a428c09856 100644 --- a/twilio/rest/ip_messaging/v1/service/user/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/user/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,6 +76,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -111,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserInstance": """ Fetch the UserInstance @@ -129,6 +149,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, role_sid: Union[str, object] = values.unset, @@ -171,6 +209,48 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + @property def user_channels(self) -> UserChannelList: """ @@ -209,6 +289,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._user_channels: Optional[UserChannelList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserInstance @@ -216,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: @@ -228,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: @@ -240,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: """ @@ -260,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, @@ -295,13 +471,34 @@ 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, + 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, @@ -309,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, @@ -331,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, @@ -345,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: """ @@ -376,6 +644,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserInstance: :param payload: Payload response from the API """ + return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -407,22 +676,18 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Users".format(**self._solution) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Create the UserInstance + Internal helper for create operation - :param identity: - :param role_sid: - :param attributes: - :param friendly_name: - - :returns: The created UserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -435,30 +700,81 @@ def create( ) headers = values.of({"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, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + payload, _, _ = self._create( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> ApiResponse: """ - Asynchronously create the UserInstance + Create the UserInstance and return response metadata :param identity: :param role_sid: :param attributes: :param friendly_name: - :returns: The created UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -471,14 +787,69 @@ async def create_async( ) headers = values.of({"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, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the UserInstance and return response metadata + + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -529,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, @@ -548,6 +969,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -574,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( @@ -582,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, @@ -606,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, @@ -633,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: """ @@ -648,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: """ @@ -660,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 192aafb380..28ee7b4930 100644 --- a/twilio/rest/ip_messaging/v1/service/user/user_channel.py +++ b/twilio/rest/ip_messaging/v1/service/user/user_channel.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -82,6 +83,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: :param payload: Payload response from the API """ + return UserChannelInstance( self._version, payload, @@ -170,6 +172,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -189,6 +241,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -215,6 +268,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -223,6 +277,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UserChannelInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -247,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, @@ -274,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: """ @@ -289,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: """ @@ -301,7 +485,7 @@ async def get_page_async(self, target_url: str) -> UserChannelPage: :returns: Page of UserChannelInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UserChannelPage(self._version, response, self._solution) + return UserChannelPage(self._version, response, solution=self._solution) def __repr__(self) -> str: """ diff --git a/twilio/rest/ip_messaging/v2/credential.py b/twilio/rest/ip_messaging/v2/credential.py index 5d4e14f983..7032a6e2f3 100644 --- a/twilio/rest/ip_messaging/v2/credential.py +++ b/twilio/rest/ip_messaging/v2/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -174,6 +212,66 @@ async def update_async( secret=secret, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,6 +299,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -208,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: @@ -220,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: @@ -232,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: """ @@ -251,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, @@ -284,6 +514,64 @@ 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, @@ -294,14 +582,15 @@ def update( "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, @@ -324,24 +613,47 @@ async def update_async( :returns: The updated CredentialInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": serialize.boolean_to_string(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: """ @@ -361,6 +673,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: :param payload: Payload response from the API """ + return CredentialInstance(self._version, payload) def __repr__(self) -> str: @@ -385,7 +698,7 @@ def __init__(self, version: Version): self._uri = "/Credentials" - def create( + def _create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -394,19 +707,12 @@ def create( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Create the CredentialInstance + Internal helper for create operation - :param type: - :param friendly_name: - :param certificate: - :param private_key: - :param sandbox: - :param api_key: - :param secret: - - :returns: The created CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -422,13 +728,15 @@ def create( ) headers = values.of({"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 CredentialInstance(self._version, payload) - - async def create_async( + def create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -439,7 +747,7 @@ async def create_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronously create the CredentialInstance + Create the CredentialInstance :param type: :param friendly_name: @@ -451,6 +759,68 @@ async def create_async( :returns: The created CredentialInstance """ + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -465,12 +835,83 @@ async def create_async( ) headers = values.of({"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, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance + """ + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload) + async def create_with_http_info_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -521,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, @@ -540,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -566,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( @@ -574,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, @@ -598,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( @@ -625,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 3475811625..a00dfed962 100644 --- a/twilio/rest/ip_messaging/v2/service/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -103,6 +104,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -138,6 +140,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -156,6 +176,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -370,129 +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, @@ -527,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: @@ -563,67 +479,43 @@ def update( :param post_webhook_retry_count: :param notifications_log_enabled: - :returns: The updated ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": serialize.boolean_to_string( - notifications_new_message_enabled - ), - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.NewMessage.Sound": notifications_new_message_sound, - "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( - notifications_new_message_badge_count_enabled - ), - "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( - notifications_added_to_channel_enabled - ), - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, - "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( - notifications_removed_from_channel_enabled - ), - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, - "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( - notifications_invited_to_channel_enabled - ), - "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, - "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "WebhookMethod": webhook_method, - "WebhookFilters": serialize.map(webhook_filters, lambda e: e), - "Limits.ChannelMembers": limits_channel_members, - "Limits.UserChannels": limits_user_channels, - "Media.CompatibilityMessage": media_compatibility_message, - "PreWebhookRetryCount": pre_webhook_retry_count, - "PostWebhookRetryCount": post_webhook_retry_count, - "Notifications.LogEnabled": serialize.boolean_to_string( - notifications_log_enabled - ), - } - ) - - 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, @@ -658,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: @@ -694,42 +586,656 @@ async def update_async( :param post_webhook_retry_count: :param notifications_log_enabled: - :returns: The updated ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), - "ReachabilityEnabled": serialize.boolean_to_string( - reachability_enabled - ), - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "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, + 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, @@ -745,14 +1251,232 @@ async def update_async( ), } ) + 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 - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + :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: - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + :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: @@ -820,6 +1544,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -844,13 +1569,12 @@ def __init__(self, version: Version): self._uri = "/Services" - def create(self, friendly_name: str) -> ServiceInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the ServiceInstance + Internal helper for create operation - :param friendly_name: - - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -860,19 +1584,43 @@ def create(self, friendly_name: str) -> ServiceInstance: ) headers = values.of({"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, 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( @@ -882,12 +1630,39 @@ async def create_async(self, friendly_name: str) -> ServiceInstance: ) headers = values.of({"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, 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, @@ -938,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, @@ -957,6 +1782,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -983,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( @@ -991,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, @@ -1015,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( @@ -1042,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 24c4f65a4b..b7394ff7a1 100644 --- a/twilio/rest/ip_messaging/v2/service/binding.py +++ b/twilio/rest/ip_messaging/v2/service/binding.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[BindingContext] = None @property @@ -112,6 +114,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "BindingInstance": """ Fetch the BindingInstance @@ -130,6 +150,24 @@ async def fetch_async(self) -> "BindingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -159,6 +197,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the BindingInstance @@ -166,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: @@ -178,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: @@ -190,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: """ @@ -210,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: """ @@ -241,6 +377,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: :param payload: Payload response from the API """ + return BindingInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -334,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, @@ -357,6 +554,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -389,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( @@ -399,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, @@ -429,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, @@ -462,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: """ @@ -477,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: """ @@ -489,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 29ee9ddd64..5dd5288a73 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/channel/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -89,6 +90,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[ChannelContext] = None @property @@ -141,6 +143,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "ChannelInstance": """ Fetch the ChannelInstance @@ -159,6 +195,24 @@ async def fetch_async(self) -> "ChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -229,6 +283,76 @@ async def update_async( created_by=created_by, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChannelInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + @property def invites(self) -> InviteList: """ @@ -291,6 +415,30 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._messages: Optional[MessageList] = None self._webhooks: Optional[WebhookList] = None + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -304,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, @@ -325,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: @@ -342,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: """ @@ -362,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 @@ -386,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 - - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param friendly_name: - :param unique_name: - :param attributes: - :param date_created: - :param date_updated: - :param created_by: + Internal helper for update operation - :returns: The updated ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -410,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 @@ -440,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: @@ -452,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, @@ -479,8 +716,181 @@ async def update_async( sid=self._solution["sid"], ) - @property - def invites(self) -> InviteList: + 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 """ @@ -549,6 +959,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: :param payload: Payload response from the API """ + return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -580,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 @@ -592,20 +1003,12 @@ def create( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, created_by: Union[str, object] = values.unset, - ) -> ChannelInstance: + ) -> tuple: """ - Create the ChannelInstance - - :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( @@ -626,15 +1029,56 @@ def create( } ) - 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 @@ -646,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: @@ -659,7 +1103,41 @@ async def create_async( :param date_updated: :param created_by: - :returns: The created ChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + instance = ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -680,14 +1158,97 @@ async def create_async( } ) - 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, @@ -742,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, @@ -763,6 +1380,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -792,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( @@ -801,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, @@ -828,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, @@ -858,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: """ @@ -873,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: """ @@ -885,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 a40c47a125..3faf373020 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/invite.py +++ b/twilio/rest/ip_messaging/v2/service/channel/invite.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InviteContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InviteInstance": """ Fetch the InviteInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "InviteInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InviteInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,6 +194,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InviteInstance @@ -163,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: @@ -175,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: @@ -187,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: """ @@ -208,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: """ @@ -240,6 +378,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: :param payload: Payload response from the API """ + return InviteInstance( self._version, payload, @@ -278,16 +417,14 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> tuple: """ - Create the InviteInstance - - :param identity: - :param role_sid: + Internal helper for create operation - :returns: The created InviteInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -298,10 +435,26 @@ def create( ) headers = values.of({"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, 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, @@ -309,16 +462,36 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, identity: str, role_sid: Union[str, object] = values.unset - ) -> InviteInstance: + ) -> ApiResponse: """ - Asynchronously create the InviteInstance + Create the InviteInstance and return response metadata :param identity: :param role_sid: - :returns: The created InviteInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, role_sid=role_sid + ) + instance = InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -329,10 +502,26 @@ async def create_async( ) headers = values.of({"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, 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, @@ -340,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, @@ -394,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, @@ -415,6 +682,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -444,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( @@ -453,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, @@ -480,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, @@ -510,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: """ @@ -525,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: """ @@ -537,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 9511a2bf6b..580bbbe1a4 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/member.py +++ b/twilio/rest/ip_messaging/v2/service/channel/member.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MemberContext] = None @property @@ -132,6 +134,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "MemberInstance": """ Fetch the MemberInstance @@ -150,6 +186,24 @@ async def fetch_async(self) -> "MemberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MemberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -220,6 +274,76 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MemberInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -255,6 +379,30 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -268,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, @@ -289,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: @@ -306,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: """ @@ -327,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 @@ -352,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, @@ -378,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 @@ -409,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: @@ -421,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, @@ -451,13 +687,191 @@ async def update_async( 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()) + 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 + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) return "".format(context) @@ -469,6 +883,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -507,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[ @@ -519,20 +934,12 @@ def create( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MemberInstance: + ) -> tuple: """ - Create the MemberInstance - - :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: + Internal helper for create operation - :returns: The created MemberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -555,10 +962,51 @@ def create( } ) - 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, @@ -566,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[ @@ -578,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 @@ -591,7 +1039,44 @@ async def create_async( :param date_updated: :param attributes: - :returns: The created MemberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + instance = MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -614,10 +1099,51 @@ async def create_async( } ) - 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, @@ -625,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, @@ -679,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, @@ -700,6 +1327,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -729,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( @@ -738,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, @@ -765,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, @@ -795,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: """ @@ -810,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: """ @@ -822,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 7420117113..f53ed8a70b 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/message.py +++ b/twilio/rest/ip_messaging/v2/service/channel/message.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -87,6 +88,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -140,6 +142,40 @@ async def delete_async( x_twilio_webhook_enabled=x_twilio_webhook_enabled, ) + def delete_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + def fetch(self) -> "MessageInstance": """ Fetch the MessageInstance @@ -158,6 +194,24 @@ async def fetch_async(self) -> "MessageInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -228,6 +282,76 @@ async def update_async( from_=from_, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessageInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -263,6 +387,30 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete( self, x_twilio_webhook_enabled: Union[ @@ -276,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, @@ -297,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: @@ -314,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: """ @@ -335,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 @@ -360,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, @@ -384,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 @@ -415,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: @@ -427,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, @@ -455,15 +693,191 @@ async def update_async( 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) - + 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): @@ -473,6 +887,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: :param payload: Payload response from the API """ + return MessageInstance( self._version, payload, @@ -511,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 @@ -523,20 +938,12 @@ def create( last_updated_by: Union[str, object] = values.unset, body: Union[str, object] = values.unset, media_sid: Union[str, object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Create the MessageInstance - - :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( @@ -557,10 +964,51 @@ def create( } ) - 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, @@ -568,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 @@ -580,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_: @@ -593,7 +1041,44 @@ async def create_async( :param body: :param media_sid: - :returns: The created MessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + from_=from_, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + body=body, + media_sid=media_sid, + ) + instance = MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -614,10 +1099,51 @@ async def create_async( } ) - 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, @@ -625,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, @@ -679,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, @@ -700,6 +1327,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -729,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( @@ -738,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, @@ -765,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, @@ -795,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: """ @@ -810,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: """ @@ -822,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 db23dd66af..a72375bb7a 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/webhook.py +++ b/twilio/rest/ip_messaging/v2/service/channel/webhook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[WebhookContext] = None @property @@ -111,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WebhookInstance": """ Fetch the WebhookInstance @@ -129,6 +149,24 @@ async def fetch_async(self) -> "WebhookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, configuration_url: Union[str, object] = values.unset, @@ -189,6 +227,66 @@ async def update_async( configuration_retry_count=configuration_retry_count, ) + def update_with_http_info( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + + async def update_with_http_info_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -224,6 +322,20 @@ def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WebhookInstance @@ -231,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: @@ -243,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: @@ -255,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: """ @@ -276,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, @@ -298,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 + Internal helper for update operation - :param configuration_url: - :param configuration_method: - :param configuration_filters: - :param configuration_triggers: - :param configuration_flow_sid: - :param configuration_retry_count: - - :returns: The updated WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Configuration.Url": configuration_url, @@ -325,13 +518,45 @@ def update( "Configuration.RetryCount": configuration_retry_count, } ) + 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, + 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, @@ -340,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, @@ -348,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: @@ -359,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, @@ -375,49 +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) - - -class WebhookPage(Page): + Asynchronous coroutine to update the WebhookInstance - 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 """ @@ -446,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, @@ -455,19 +784,12 @@ def create( configuration_triggers: Union[List[str], object] = values.unset, configuration_flow_sid: Union[str, object] = values.unset, configuration_retry_count: Union[int, object] = values.unset, - ) -> WebhookInstance: + ) -> tuple: """ - Create the WebhookInstance - - :param type: - :param configuration_url: - :param configuration_method: - :param configuration_filters: - :param configuration_triggers: - :param configuration_flow_sid: - :param configuration_retry_count: + Internal helper for create operation - :returns: The created WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -487,10 +809,46 @@ def create( ) headers = values.of({"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, + 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, @@ -498,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, @@ -507,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: @@ -519,7 +877,40 @@ async def create_async( :param configuration_flow_sid: :param configuration_retry_count: - :returns: The created WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + instance = WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -539,10 +930,46 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -550,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, @@ -600,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, @@ -619,6 +1136,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -645,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( @@ -653,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, @@ -677,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, @@ -704,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: """ @@ -719,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: """ @@ -731,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 0acf77983b..02f3e055e0 100644 --- a/twilio/rest/ip_messaging/v2/service/role.py +++ b/twilio/rest/ip_messaging/v2/service/role.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[RoleContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoleInstance": """ Fetch the RoleInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "RoleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, permission: List[str]) -> "RoleInstance": """ Update the RoleInstance @@ -145,6 +183,30 @@ async def update_async(self, permission: List[str]) -> "RoleInstance": permission=permission, ) + def update_with_http_info(self, permission: List[str]) -> ApiResponse: + """ + Update the RoleInstance with HTTP info + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + permission=permission, + ) + + async def update_with_http_info_async(self, permission: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the RoleInstance with HTTP info + + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + permission=permission, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -174,6 +236,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoleInstance @@ -181,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: @@ -193,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: @@ -205,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: """ @@ -225,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, @@ -238,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({}) + + 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, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + payload, _, _ = self._update(permission=permission) return RoleInstance( self._version, payload, @@ -265,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, @@ -292,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 @@ -310,6 +528,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -341,17 +560,14 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Roles".format(**self._solution) - def create( + def _create( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> tuple: """ - Create the RoleInstance + Internal helper for create operation - :param friendly_name: - :param type: - :param permission: - - :returns: The created RoleInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -363,25 +579,61 @@ def create( ) headers = values.of({"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, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] - ) -> RoleInstance: + ) -> ApiResponse: """ - Asynchronously create the RoleInstance + Create the RoleInstance and return response metadata :param friendly_name: :param type: :param permission: - :returns: The created RoleInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -393,14 +645,53 @@ async def create_async( ) headers = values.of({"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, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata + + :param friendly_name: + :param type: + :param permission: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission + ) + instance = RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -451,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, @@ -470,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -496,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( @@ -504,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, @@ -528,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, @@ -555,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: """ @@ -570,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: """ @@ -582,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 3af3121fab..b6eb03d7f4 100644 --- a/twilio/rest/ip_messaging/v2/service/user/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/user/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -81,6 +82,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -117,6 +119,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserInstance": """ Fetch the UserInstance @@ -135,6 +155,24 @@ async def fetch_async(self) -> "UserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, x_twilio_webhook_enabled: Union[ @@ -187,6 +225,58 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserInstance with HTTP info + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + @property def user_bindings(self) -> UserBindingList: """ @@ -233,6 +323,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._user_bindings: Optional[UserBindingList] = None self._user_channels: Optional[UserChannelList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserInstance @@ -240,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: @@ -252,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: @@ -264,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: """ @@ -284,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 @@ -305,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, @@ -323,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, @@ -340,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 @@ -348,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, @@ -366,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, @@ -383,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: """ @@ -427,6 +743,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserInstance: :param payload: Payload response from the API """ + return UserInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -458,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[ @@ -467,17 +784,12 @@ def create( role_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, - ) -> UserInstance: + ) -> tuple: """ - Create the UserInstance - - :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( @@ -495,15 +807,47 @@ def create( } ) - 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[ @@ -512,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 @@ -522,7 +866,35 @@ async def create_async( :param attributes: :param friendly_name: - :returns: The created UserInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + instance = UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -540,14 +912,79 @@ async def create_async( } ) - 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, @@ -598,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, @@ -617,6 +1104,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -643,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( @@ -651,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, @@ -675,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, @@ -702,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: """ @@ -717,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: """ @@ -729,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 575a295cbb..cf7b3f7fc9 100644 --- a/twilio/rest/ip_messaging/v2/service/user/user_binding.py +++ b/twilio/rest/ip_messaging/v2/service/user/user_binding.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -78,6 +79,7 @@ def __init__( "user_sid": user_sid, "sid": sid or self.sid, } + self._context: Optional[UserBindingContext] = None @property @@ -115,6 +117,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserBindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserBindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserBindingInstance": """ Fetch the UserBindingInstance @@ -133,6 +153,24 @@ async def fetch_async(self) -> "UserBindingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserBindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserBindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -166,6 +204,20 @@ def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserBindingInstance @@ -173,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: @@ -185,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: @@ -197,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: """ @@ -218,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: """ @@ -250,6 +388,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: :param payload: Payload response from the API """ + return UserBindingInstance( self._version, payload, @@ -348,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[ @@ -371,6 +570,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -402,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( @@ -411,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[ @@ -440,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, @@ -472,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: """ @@ -487,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: """ @@ -499,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 d89e6cb80d..db12f64be8 100644 --- a/twilio/rest/ip_messaging/v2/service/user/user_channel.py +++ b/twilio/rest/ip_messaging/v2/service/user/user_channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -82,6 +83,7 @@ def __init__( "user_sid": user_sid, "channel_sid": channel_sid or self.channel_sid, } + self._context: Optional[UserChannelContext] = None @property @@ -119,6 +121,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UserChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "UserChannelInstance": """ Fetch the UserChannelInstance @@ -137,6 +157,24 @@ async def fetch_async(self) -> "UserChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UserChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, notification_level: Union[ @@ -183,6 +221,52 @@ async def update_async( last_consumption_timestamp=last_consumption_timestamp, ) + def update_with_http_info( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Update the UserChannelInstance with HTTP info + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + + async def update_with_http_info_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UserChannelInstance with HTTP info + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -220,6 +304,20 @@ def __init__( ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UserChannelInstance @@ -227,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: @@ -239,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: @@ -251,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: """ @@ -272,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 - - :param notification_level: - :param last_consumed_message_index: - :param last_consumption_timestamp: + Internal helper for update operation - :returns: The updated UserChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "NotificationLevel": notification_level, @@ -312,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, @@ -327,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, @@ -353,13 +589,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: + :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, @@ -368,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 @@ -386,6 +678,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: :param payload: Payload response from the API """ + return UserChannelInstance( self._version, payload, @@ -474,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, @@ -493,6 +836,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -519,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( @@ -527,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, @@ -551,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, @@ -578,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: """ @@ -593,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: """ @@ -605,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 d84c79039b..9609bff951 100644 --- a/twilio/rest/preview/sync/__init__.py +++ b/twilio/rest/knowledge/v1/__init__.py @@ -4,7 +4,7 @@ | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - Twilio - Preview + Twilio - Knowledge This is the public Twilio REST API. NOTE: This class is auto generated by OpenAPI Generator. @@ -15,29 +15,29 @@ from typing import Optional from twilio.base.version import Version from twilio.base.domain import Domain -from twilio.rest.preview.sync.service import ServiceList +from twilio.rest.knowledge.v1.knowledge import KnowledgeList -class Sync(Version): +class V1(Version): def __init__(self, domain: Domain): """ - Initialize the Sync version of Preview + Initialize the V1 version of Knowledge - :param domain: The Twilio.preview domain + :param domain: The Twilio.knowledge domain """ - super().__init__(domain, "Sync") - self._services: Optional[ServiceList] = None + super().__init__(domain, "v1") + self._knowledge: Optional[KnowledgeList] = None @property - def services(self) -> ServiceList: - if self._services is None: - self._services = ServiceList(self) - return self._services + def knowledge(self) -> KnowledgeList: + if self._knowledge is None: + self._knowledge = KnowledgeList(self) + return self._knowledge def __repr__(self) -> str: """ Provide a friendly representation :returns: Machine friendly representation """ - return "" + return "" diff --git a/twilio/rest/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/v1/phone_number.py b/twilio/rest/lookups/v1/phone_number.py index fe521c73e9..66ac1d0d6e 100644 --- a/twilio/rest/lookups/v1/phone_number.py +++ b/twilio/rest/lookups/v1/phone_number.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -50,6 +51,7 @@ def __init__( self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[PhoneNumberContext] = None @property @@ -78,7 +80,7 @@ def fetch( Fetch the PhoneNumberInstance :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. - :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. Carrier information costs $0.005 per phone number looked up. Caller Name information is currently available only in the US and costs $0.01 per phone number looked up. To retrieve both types on information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. @@ -102,7 +104,7 @@ async def fetch_async( Asynchronous coroutine to fetch the PhoneNumberInstance :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. - :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. Carrier information costs $0.005 per phone number looked up. Caller Name information is currently available only in the US and costs $0.01 per phone number looked up. To retrieve both types on information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. @@ -115,6 +117,54 @@ async def fetch_async( add_ons_data=add_ons_data, ) + def fetch_with_http_info( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + + async def fetch_with_http_info_async( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -142,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) - data = values.of( + async def _fetch_async( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "CountryCode": country_code, "Type": serialize.map(type, lambda e: e), "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 diff --git a/twilio/rest/lookups/v2/__init__.py b/twilio/rest/lookups/v2/__init__.py index d795aea168..852f552540 100644 --- a/twilio/rest/lookups/v2/__init__.py +++ b/twilio/rest/lookups/v2/__init__.py @@ -15,7 +15,11 @@ from typing import Optional from twilio.base.version import Version from twilio.base.domain import Domain +from twilio.rest.lookups.v2.bucket import BucketList +from twilio.rest.lookups.v2.lookup_override import LookupOverrideList from twilio.rest.lookups.v2.phone_number import PhoneNumberList +from twilio.rest.lookups.v2.query import QueryList +from twilio.rest.lookups.v2.rate_limit import RateLimitList class V2(Version): @@ -27,7 +31,23 @@ def __init__(self, domain: Domain): :param domain: The Twilio.lookups domain """ super().__init__(domain, "v2") + self._bucket: Optional[BucketList] = None + self._lookup_overrides: Optional[LookupOverrideList] = None self._phone_numbers: Optional[PhoneNumberList] = None + self._query: Optional[QueryList] = None + self._rate_limits: Optional[RateLimitList] = None + + @property + def bucket(self) -> BucketList: + if self._bucket is None: + self._bucket = BucketList(self) + return self._bucket + + @property + def lookup_overrides(self) -> LookupOverrideList: + if self._lookup_overrides is None: + self._lookup_overrides = LookupOverrideList(self) + return self._lookup_overrides @property def phone_numbers(self) -> PhoneNumberList: @@ -35,6 +55,18 @@ def phone_numbers(self) -> PhoneNumberList: self._phone_numbers = PhoneNumberList(self) return self._phone_numbers + @property + def query(self) -> QueryList: + if self._query is None: + self._query = QueryList(self) + return self._query + + @property + def rate_limits(self) -> RateLimitList: + if self._rate_limits is None: + self._rate_limits = RateLimitList(self) + return self._rate_limits + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/lookups/v2/bucket.py b/twilio/rest/lookups/v2/bucket.py new file mode 100644 index 0000000000..ce020fa8f3 --- /dev/null +++ b/twilio/rest/lookups/v2/bucket.py @@ -0,0 +1,621 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Lookups + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BucketInstance(InstanceResource): + + class RateLimitRequest(object): + """ + :ivar limit: Limit of requests for the bucket + :ivar ttl: Time to live of the rule + """ + + def __init__(self, payload: Dict[str, Any]): + + self.limit: Optional[int] = payload.get("limit") + self.ttl: Optional[int] = payload.get("ttl") + + def to_dict(self): + return { + "limit": self.limit, + "ttl": self.ttl, + } + + """ + :ivar code: Twilio-specific error code + :ivar message: Error message + :ivar more_info: Link to Error Code References + :ivar status: HTTP response status code + :ivar field: Limit of requests for the bucket + :ivar limit: Limit of requests for the bucket + :ivar bucket: Name of the bucket + :ivar owner: Owner of the rule + :ivar ttl: Time to live of the rule + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + field: Optional[str] = None, + bucket: Optional[str] = None, + ): + super().__init__(version) + + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.more_info: Optional[str] = payload.get("more_info") + self.status: Optional[int] = payload.get("status") + self.field: Optional[str] = payload.get("field") + self.limit: Optional[int] = payload.get("limit") + self.bucket: Optional[str] = payload.get("bucket") + self.owner: Optional[str] = payload.get("owner") + self.ttl: Optional[int] = payload.get("ttl") + + self._solution = { + "field": field or self.field, + "bucket": bucket or self.bucket, + } + + self._context: Optional[BucketContext] = None + + @property + def _proxy(self) -> "BucketContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BucketContext for this BucketInstance + """ + if self._context is None: + self._context = BucketContext( + self._version, + field=self._solution["field"], + bucket=self._solution["bucket"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BucketInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BucketInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "BucketInstance": + """ + Fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BucketInstance": + """ + Asynchronous coroutine to fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BucketInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BucketInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> "BucketInstance": + """ + Update the BucketInstance + + :param rate_limit_request: + + :returns: The updated BucketInstance + """ + return self._proxy.update( + rate_limit_request=rate_limit_request, + ) + + async def update_async( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> "BucketInstance": + """ + Asynchronous coroutine to update the BucketInstance + + :param rate_limit_request: + + :returns: The updated BucketInstance + """ + return await self._proxy.update_async( + rate_limit_request=rate_limit_request, + ) + + def update_with_http_info( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> ApiResponse: + """ + Update the BucketInstance with HTTP info + + :param rate_limit_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + rate_limit_request=rate_limit_request, + ) + + async def update_with_http_info_async( + self, rate_limit_request: Union[RateLimitRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BucketInstance with HTTP info + + :param rate_limit_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + rate_limit_request=rate_limit_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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 d9c73c22d8..2240351721 100644 --- a/twilio/rest/lookups/v2/phone_number.py +++ b/twilio/rest/lookups/v2/phone_number.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -37,14 +38,14 @@ class ValidationError(object): :ivar national_format: The phone number in [national format](https://en.wikipedia.org/wiki/National_conventions_for_writing_telephone_numbers). :ivar valid: Boolean which indicates if the phone number is in a valid range that can be freely assigned by a carrier to a user. :ivar validation_errors: Contains reasons why a phone number is invalid. Possible values: TOO_SHORT, TOO_LONG, INVALID_BUT_POSSIBLE, INVALID_COUNTRY_CODE, INVALID_LENGTH, NOT_A_NUMBER. - :ivar caller_name: An object that contains caller name information based on [CNAM](https://support.twilio.com/hc/en-us/articles/360051670533-Getting-Started-with-CNAM-Caller-ID). - :ivar sim_swap: An object that contains information on the last date the subscriber identity module (SIM) was changed for a mobile phone number. - :ivar call_forwarding: An object that contains information on the unconditional call forwarding status of mobile phone number. - :ivar line_status: An object that contains line status information for a mobile phone number. - :ivar line_type_intelligence: An object that contains line type information including the carrier name, mobile country code, and mobile network code. - :ivar identity_match: An object that contains identity match information. The result of comparing user-provided information including name, address, date of birth, national ID, against authoritative phone-based data sources - :ivar reassigned_number: An object that contains reassigned number information. Reassigned Numbers will return a phone number's reassignment status given a phone number and date - :ivar sms_pumping_risk: An object that contains information on if a phone number has been currently or previously blocked by Verify Fraud Guard for receiving malicious SMS pumping traffic as well as other signals associated with risky carriers and low conversion rates. + :ivar caller_name: + :ivar sim_swap: + :ivar call_forwarding: + :ivar line_type_intelligence: + :ivar line_status: + :ivar identity_match: + :ivar reassigned_number: + :ivar sms_pumping_risk: :ivar phone_number_quality_score: An object that contains information of a mobile phone number quality score. Quality score will return a risk score about the phone number. :ivar pre_fill: An object that contains pre fill information. pre_fill will return PII information associated with the phone number like first name, last name, address line, country code, state and postal code. :ivar url: The absolute URL of the resource. @@ -63,25 +64,19 @@ def __init__( self.phone_number: Optional[str] = payload.get("phone_number") self.national_format: Optional[str] = payload.get("national_format") self.valid: Optional[bool] = payload.get("valid") - self.validation_errors: Optional[ - List["PhoneNumberInstance.ValidationError"] - ] = payload.get("validation_errors") - self.caller_name: Optional[Dict[str, object]] = payload.get("caller_name") - self.sim_swap: Optional[Dict[str, object]] = payload.get("sim_swap") - self.call_forwarding: Optional[Dict[str, object]] = payload.get( - "call_forwarding" + self.validation_errors: Optional[List[Enumstr]] = payload.get( + "validation_errors" ) - self.line_status: Optional[Dict[str, object]] = payload.get("line_status") - self.line_type_intelligence: Optional[Dict[str, object]] = payload.get( + self.caller_name: Optional[str] = payload.get("caller_name") + self.sim_swap: Optional[str] = payload.get("sim_swap") + self.call_forwarding: Optional[str] = payload.get("call_forwarding") + self.line_type_intelligence: Optional[str] = payload.get( "line_type_intelligence" ) - self.identity_match: Optional[Dict[str, object]] = payload.get("identity_match") - self.reassigned_number: Optional[Dict[str, object]] = payload.get( - "reassigned_number" - ) - self.sms_pumping_risk: Optional[Dict[str, object]] = payload.get( - "sms_pumping_risk" - ) + self.line_status: Optional[str] = payload.get("line_status") + self.identity_match: Optional[str] = payload.get("identity_match") + self.reassigned_number: Optional[str] = payload.get("reassigned_number") + self.sms_pumping_risk: Optional[str] = payload.get("sms_pumping_risk") self.phone_number_quality_score: Optional[Dict[str, object]] = payload.get( "phone_number_quality_score" ) @@ -91,6 +86,7 @@ def __init__( self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[PhoneNumberContext] = None @property @@ -124,6 +120,7 @@ def fetch( date_of_birth: Union[str, object] = values.unset, last_verified_date: Union[str, object] = values.unset, verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, ) -> "PhoneNumberInstance": """ Fetch the PhoneNumberInstance @@ -142,6 +139,7 @@ def fetch( :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. :returns: The fetched PhoneNumberInstance """ @@ -160,6 +158,7 @@ def fetch( date_of_birth=date_of_birth, last_verified_date=last_verified_date, verification_sid=verification_sid, + partner_sub_id=partner_sub_id, ) async def fetch_async( @@ -178,6 +177,7 @@ async def fetch_async( date_of_birth: Union[str, object] = values.unset, last_verified_date: Union[str, object] = values.unset, verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, ) -> "PhoneNumberInstance": """ Asynchronous coroutine to fetch the PhoneNumberInstance @@ -196,6 +196,7 @@ async def fetch_async( :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. :returns: The fetched PhoneNumberInstance """ @@ -214,6 +215,121 @@ async def fetch_async( date_of_birth=date_of_birth, last_verified_date=last_verified_date, verification_sid=verification_sid, + partner_sub_id=partner_sub_id, + ) + + def fetch_with_http_info( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + fields=fields, + country_code=country_code, + first_name=first_name, + last_name=last_name, + address_line1=address_line1, + address_line2=address_line2, + city=city, + state=state, + postal_code=postal_code, + address_country_code=address_country_code, + national_id=national_id, + date_of_birth=date_of_birth, + last_verified_date=last_verified_date, + verification_sid=verification_sid, + partner_sub_id=partner_sub_id, + ) + + async def fetch_with_http_info_async( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + fields=fields, + country_code=country_code, + first_name=first_name, + last_name=last_name, + address_line1=address_line1, + address_line2=address_line2, + city=city, + state=state, + postal_code=postal_code, + address_country_code=address_country_code, + national_id=national_id, + date_of_birth=date_of_birth, + last_verified_date=last_verified_date, + verification_sid=verification_sid, + partner_sub_id=partner_sub_id, ) def __repr__(self) -> str: @@ -243,7 +359,7 @@ def __init__(self, version: Version, phone_number: str): } self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) - def fetch( + def _fetch( self, fields: Union[str, object] = values.unset, country_code: Union[str, object] = values.unset, @@ -259,29 +375,16 @@ def fetch( date_of_birth: Union[str, object] = values.unset, last_verified_date: Union[str, object] = values.unset, verification_sid: Union[str, object] = values.unset, - ) -> PhoneNumberInstance: + partner_sub_id: Union[str, object] = values.unset, + ) -> tuple: """ - Fetch the PhoneNumberInstance - - :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. - :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. - :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. - :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. - :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. - :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. - :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. - :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. - :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. - :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. - :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. - :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. - :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. - :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + Internal helper for fetch operation - :returns: The fetched PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Fields": fields, "CountryCode": country_code, @@ -297,18 +400,81 @@ def fetch( "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, @@ -324,9 +490,10 @@ async def fetch_async( date_of_birth: Union[str, object] = values.unset, last_verified_date: Union[str, object] = values.unset, verification_sid: Union[str, object] = values.unset, - ) -> PhoneNumberInstance: + partner_sub_id: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the PhoneNumberInstance + Fetch the PhoneNumberInstance and return response metadata :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. @@ -342,11 +509,60 @@ async def fetch_async( :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. - :returns: The fetched PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + fields=fields, + country_code=country_code, + first_name=first_name, + last_name=last_name, + address_line1=address_line1, + address_line2=address_line2, + city=city, + state=state, + postal_code=postal_code, + address_country_code=address_country_code, + national_id=national_id, + date_of_birth=date_of_birth, + last_verified_date=last_verified_date, + verification_sid=verification_sid, + partner_sub_id=partner_sub_id, + ) + instance = PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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, @@ -362,19 +578,143 @@ async def fetch_async( "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 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/__init__.py b/twilio/rest/marketplace/__init__.py index 79b10ef6c4..f0276a8f84 100644 --- a/twilio/rest/marketplace/__init__.py +++ b/twilio/rest/marketplace/__init__.py @@ -7,4 +7,3 @@ def available_add_ons(self): 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 index 49fc490396..6a84b31cd9 100644 --- a/twilio/rest/marketplace/v1/__init__.py +++ b/twilio/rest/marketplace/v1/__init__.py @@ -17,7 +17,9 @@ 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): @@ -31,7 +33,9 @@ def __init__(self, domain: 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: @@ -45,12 +49,24 @@ def installed_add_ons(self) -> InstalledAddOnList: 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 diff --git a/twilio/rest/marketplace/v1/available_add_on/__init__.py b/twilio/rest/marketplace/v1/available_add_on/__init__.py index 6f6713ee17..53ed2aeb1d 100644 --- a/twilio/rest/marketplace/v1/available_add_on/__init__.py +++ b/twilio/rest/marketplace/v1/available_add_on/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AvailableAddOnContext] = None @property @@ -88,6 +90,24 @@ async def fetch_async(self) -> "AvailableAddOnInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def extensions(self) -> AvailableAddOnExtensionList: """ @@ -124,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 @@ -131,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: """ @@ -150,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: @@ -192,6 +264,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnInstance: :param payload: Payload response from the API """ + return AvailableAddOnInstance(self._version, payload) def __repr__(self) -> str: @@ -266,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, @@ -285,6 +408,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -311,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( @@ -319,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, @@ -343,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( @@ -370,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/marketplace/v1/available_add_on/available_add_on_extension.py b/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py index 1113d9313c..14dcfed3af 100644 --- a/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py +++ b/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( "available_add_on_sid": available_add_on_sid, "sid": sid or self.sid, } + self._context: Optional[AvailableAddOnExtensionContext] = None @property @@ -87,6 +89,24 @@ async def fetch_async(self) -> "AvailableAddOnExtensionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -120,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 @@ -127,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: """ @@ -147,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: """ @@ -180,6 +254,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnExtensionInstan :param payload: Payload response from the API """ + return AvailableAddOnExtensionInstance( self._version, payload, @@ -265,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, @@ -284,6 +409,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -310,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( @@ -318,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, @@ -342,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, @@ -369,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 ) - return AvailableAddOnExtensionPage(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 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: """ @@ -384,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: """ @@ -396,7 +663,9 @@ async def get_page_async(self, target_url: str) -> AvailableAddOnExtensionPage: :returns: Page of AvailableAddOnExtensionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + return AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> AvailableAddOnExtensionContext: """ diff --git a/twilio/rest/marketplace/v1/installed_add_on/__init__.py b/twilio/rest/marketplace/v1/installed_add_on/__init__.py index df67c01d8c..2553e78bf8 100644 --- a/twilio/rest/marketplace/v1/installed_add_on/__init__.py +++ b/twilio/rest/marketplace/v1/installed_add_on/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -65,6 +66,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[InstalledAddOnContext] = None @property @@ -100,6 +102,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InstalledAddOnInstance": """ Fetch the InstalledAddOnInstance @@ -118,6 +138,24 @@ async def fetch_async(self) -> "InstalledAddOnInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, configuration: Union[object, object] = values.unset, @@ -154,6 +192,42 @@ async def update_async( unique_name=unique_name, ) + def update_with_http_info( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the InstalledAddOnInstance with HTTP info + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + configuration=configuration, + unique_name=unique_name, + ) + + async def update_with_http_info_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnInstance with HTTP info + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + configuration=configuration, + unique_name=unique_name, + ) + @property def extensions(self) -> InstalledAddOnExtensionList: """ @@ -198,6 +272,20 @@ def __init__(self, version: Version, sid: str): self._extensions: Optional[InstalledAddOnExtensionList] = None self._usage: Optional[InstalledAddOnUsageList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InstalledAddOnInstance @@ -205,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 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: @@ -217,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 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: @@ -229,17 +363,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: """ @@ -248,17 +408,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, @@ -273,20 +471,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, @@ -301,20 +538,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: @@ -358,6 +606,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnInstance: :param payload: Payload response from the API """ + return InstalledAddOnInstance(self._version, payload) def __repr__(self) -> str: @@ -382,22 +631,18 @@ def __init__(self, version: Version): self._uri = "/InstalledAddOns" - def create( + def _create( self, available_add_on_sid: str, accept_terms_of_service: bool, configuration: Union[object, object] = values.unset, unique_name: Union[str, object] = values.unset, - ) -> InstalledAddOnInstance: + ) -> tuple: """ - Create the InstalledAddOnInstance - - :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. + Internal helper for create operation - :returns: The created InstalledAddOnInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -412,13 +657,15 @@ def create( ) headers = values.of({"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 InstalledAddOnInstance(self._version, payload) - - async def create_async( + def create( self, available_add_on_sid: str, accept_terms_of_service: bool, @@ -426,7 +673,7 @@ async def create_async( unique_name: Union[str, object] = values.unset, ) -> InstalledAddOnInstance: """ - Asynchronously create the InstalledAddOnInstance + Create the InstalledAddOnInstance :param available_add_on_sid: The SID of the AvaliableAddOn to install. :param accept_terms_of_service: Whether the Terms of Service were accepted. @@ -435,6 +682,53 @@ async def create_async( :returns: The created InstalledAddOnInstance """ + payload, _, _ = self._create( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + return InstalledAddOnInstance(self._version, payload) + + def create_with_http_info( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the InstalledAddOnInstance and return response metadata + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + instance = InstalledAddOnInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -448,12 +742,65 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -504,6 +851,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -523,6 +920,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -549,6 +947,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -557,6 +956,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists InstalledAddOnInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -581,7 +1030,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( @@ -608,11 +1063,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/marketplace/v1/installed_add_on/installed_add_on_extension.py b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py index c53a6ca510..844c78e33f 100644 --- a/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py +++ b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( "installed_add_on_sid": installed_add_on_sid, "sid": sid or self.sid, } + self._context: Optional[InstalledAddOnExtensionContext] = None @property @@ -89,6 +91,24 @@ async def fetch_async(self) -> "InstalledAddOnExtensionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, enabled: bool) -> "InstalledAddOnExtensionInstance": """ Update the InstalledAddOnExtensionInstance @@ -113,6 +133,30 @@ async def update_async(self, enabled: bool) -> "InstalledAddOnExtensionInstance" enabled=enabled, ) + def update_with_http_info(self, enabled: bool) -> ApiResponse: + """ + Update the InstalledAddOnExtensionInstance with HTTP info + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + enabled=enabled, + ) + + async def update_with_http_info_async(self, enabled: bool) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance with HTTP info + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + enabled=enabled, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -146,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 @@ -153,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: """ @@ -173,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, @@ -186,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": 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, @@ -213,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": 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, @@ -240,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 @@ -260,6 +416,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnExtensionInstan :param payload: Payload response from the API """ + return InstalledAddOnExtensionInstance( self._version, payload, @@ -345,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, @@ -364,6 +571,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -390,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( @@ -398,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, @@ -422,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, @@ -449,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 ) - return InstalledAddOnExtensionPage(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 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: """ @@ -464,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: """ @@ -476,7 +825,9 @@ async def get_page_async(self, target_url: str) -> InstalledAddOnExtensionPage: :returns: Page of InstalledAddOnExtensionInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return InstalledAddOnExtensionPage(self._version, response, self._solution) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> InstalledAddOnExtensionContext: """ diff --git a/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py index 3f9415ed49..9a2a66844b 100644 --- a/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py +++ b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -21,9 +22,57 @@ 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 billable_items: - :ivar total_submitted: Represents the total quantity 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__( @@ -31,10 +80,12 @@ def __init__( ): super().__init__(version) - self.billable_items: Optional[List[str]] = payload.get("billable_items") 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, @@ -52,39 +103,51 @@ def __repr__(self) -> str: class InstalledAddOnUsageList(ListResource): - class CreateBillingUsageRequest(object): + 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], installed_add_on_sid: str): + def __init__(self, payload: Dict[str, Any]): + self.total_submitted: Optional[float] = deserialize.decimal( + payload.get("total_submitted") + ) self.billable_items: Optional[ - List[InstalledAddOnUsageList.CreateBillingUsageRequestBillableItems] + List[ + InstalledAddOnUsageList.MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems + ] ] = payload.get("billable_items") def to_dict(self): return { - "billable_items": [ - billable_items.to_dict() for billable_items in self.billable_items - ], + "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 CreateBillingUsageRequestBillableItems(object): + class MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems(object): """ - :ivar quantity: - :ivar sid: + :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], installed_add_on_sid: str): + 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): @@ -92,7 +155,7 @@ 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: + :param installed_add_on_sid: Customer Installation SID to report usage on. """ super().__init__(version) @@ -105,56 +168,132 @@ def __init__(self, version: Version, installed_add_on_sid: str): **self._solution ) - def create( - self, create_billing_usage_request: CreateBillingUsageRequest - ) -> InstalledAddOnUsageInstance: + def _create( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> tuple: """ - Create the InstalledAddOnUsageInstance + Internal helper for create operation - :param create_billing_usage_request: - - :returns: The created InstalledAddOnUsageInstance + Returns: + tuple: (payload, status_code, headers) """ - data = create_billing_usage_request.to_dict() + 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" - payload = self._version.create( + 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"], ) - async def create_async( - self, create_billing_usage_request: CreateBillingUsageRequest - ) -> InstalledAddOnUsageInstance: + def create_with_http_info( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> ApiResponse: """ - Asynchronously create the InstalledAddOnUsageInstance + Create the InstalledAddOnUsageInstance and return response metadata - :param create_billing_usage_request: + :param marketplace_v1_installed_add_on_installed_add_on_usage: - :returns: The created InstalledAddOnUsageInstance + :returns: ApiResponse with instance, status code, and headers """ - data = create_billing_usage_request.to_dict() + 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" - payload = await self._version.create_async( + headers["Accept"] = "application/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 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 index 079a1a3343..6ac9e02d46 100644 --- a/twilio/rest/marketplace/v1/module_data_management.py +++ b/twilio/rest/marketplace/v1/module_data_management.py @@ -12,8 +12,9 @@ Do not edit the class manually. """ -from typing import Any, Dict, Optional, Union +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,13 +23,16 @@ class ModuleDataManagementInstance(InstanceResource): """ - :ivar url: - :ivar sid: - :ivar description: - :ivar support: - :ivar policies: - :ivar module_info: - :ivar documentation: + :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__( @@ -43,10 +47,14 @@ def __init__( 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 @@ -82,6 +90,24 @@ async def fetch_async(self) -> "ModuleDataManagementInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ModuleDataManagementInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ModuleDataManagementInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, module_info: Union[str, object] = values.unset, @@ -89,15 +115,19 @@ def update( 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: - :param description: - :param documentation: - :param policies: - :param support: + :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 """ @@ -107,6 +137,8 @@ def update( documentation=documentation, policies=policies, support=support, + configuration=configuration, + pricing=pricing, ) async def update_async( @@ -116,15 +148,19 @@ async def update_async( 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: - :param description: - :param documentation: - :param policies: - :param support: + :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 """ @@ -134,6 +170,74 @@ async def update_async( 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: @@ -153,7 +257,7 @@ def __init__(self, version: Version, sid: str): Initialize the ModuleDataManagementContext :param version: Version that contains the resource - :param sid: + :param sid: SID that uniquely identifies the Listing. """ super().__init__(version) @@ -163,6 +267,22 @@ def __init__(self, version: Version, sid: str): } 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 @@ -170,17 +290,43 @@ def fetch(self) -> ModuleDataManagementInstance: :returns: The fetched ModuleDataManagementInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ModuleDataManagementInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ModuleDataManagementInstance( + 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: """ @@ -189,37 +335,45 @@ async def fetch_async(self) -> ModuleDataManagementInstance: :returns: The fetched ModuleDataManagementInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ModuleDataManagementInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ModuleDataManagementInstance( + 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( + 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, - ) -> ModuleDataManagementInstance: + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> tuple: """ - Update the ModuleDataManagementInstance - - :param module_info: - :param description: - :param documentation: - :param policies: - :param support: + Internal helper for update operation - :returns: The updated ModuleDataManagementInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "ModuleInfo": module_info, @@ -227,38 +381,110 @@ def update( "Documentation": documentation, "Policies": policies, "Support": support, + "Configuration": configuration, + "Pricing": pricing, } ) + 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, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> ModuleDataManagementInstance: + """ + Update the ModuleDataManagementInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: The updated ModuleDataManagementInstance + """ + payload, _, _ = self._update( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) return ModuleDataManagementInstance( self._version, payload, sid=self._solution["sid"] ) - async def update_async( + def update_with_http_info( self, module_info: Union[str, object] = values.unset, description: Union[str, object] = values.unset, documentation: Union[str, object] = values.unset, policies: Union[str, object] = values.unset, support: Union[str, object] = values.unset, - ) -> ModuleDataManagementInstance: + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Asynchronous coroutine to update the ModuleDataManagementInstance + Update the ModuleDataManagementInstance and return response metadata - :param module_info: - :param description: - :param documentation: - :param policies: - :param support: + :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 + :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, @@ -266,19 +492,93 @@ async def update_async( "Documentation": documentation, "Policies": policies, "Support": support, + "Configuration": configuration, + "Pricing": pricing, } ) + 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, + 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 @@ -304,7 +604,7 @@ def get(self, sid: str) -> ModuleDataManagementContext: """ Constructs a ModuleDataManagementContext - :param sid: + :param sid: SID that uniquely identifies the Listing. """ return ModuleDataManagementContext(self._version, sid=sid) @@ -312,7 +612,7 @@ def __call__(self, sid: str) -> ModuleDataManagementContext: """ Constructs a ModuleDataManagementContext - :param sid: + :param sid: SID that uniquely identifies the Listing. """ return ModuleDataManagementContext(self._version, sid=sid) 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/memory/MemoryBase.py b/twilio/rest/memory/MemoryBase.py new file mode 100644 index 0000000000..1ced0e0da8 --- /dev/null +++ b/twilio/rest/memory/MemoryBase.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.memory.v1 import V1 + + +class MemoryBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Memory Domain + + :returns: Domain for Memory + """ + super().__init__(twilio, "https://memory.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Memory + """ + 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/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 4fff74d914..18b7f3e1a6 100644 --- a/twilio/rest/messaging/MessagingBase.py +++ b/twilio/rest/messaging/MessagingBase.py @@ -14,6 +14,8 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.messaging.v1 import V1 +from twilio.rest.messaging.v2 import V2 +from twilio.rest.messaging.v3 import V3 class MessagingBase(Domain): @@ -26,6 +28,8 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://messaging.twilio.com") self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + self._v3: Optional[V3] = None @property def v1(self) -> V1: @@ -36,6 +40,24 @@ def v1(self) -> V1: self._v1 = V1(self) return self._v1 + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Messaging + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Messaging + """ + if self._v3 is None: + self._v3 = V3(self) + return self._v3 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/__init__.py b/twilio/rest/messaging/v1/__init__.py index 6262dfe938..1e1100e32e 100644 --- a/twilio/rest/messaging/v1/__init__.py +++ b/twilio/rest/messaging/v1/__init__.py @@ -22,6 +22,7 @@ from twilio.rest.messaging.v1.domain_config_messaging_service import ( DomainConfigMessagingServiceList, ) +from twilio.rest.messaging.v1.domain_validate_dn import DomainValidateDnList from twilio.rest.messaging.v1.external_campaign import ExternalCampaignList from twilio.rest.messaging.v1.linkshortening_messaging_service import ( LinkshorteningMessagingServiceList, @@ -29,6 +30,7 @@ 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 @@ -50,6 +52,7 @@ def __init__(self, domain: Domain): self._domain_config_messaging_service: Optional[ DomainConfigMessagingServiceList ] = None + self._domain_validate_dns: Optional[DomainValidateDnList] = None self._external_campaign: Optional[ExternalCampaignList] = None self._linkshortening_messaging_service: Optional[ LinkshorteningMessagingServiceList @@ -57,6 +60,7 @@ def __init__(self, domain: Domain): 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 @@ -93,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: @@ -117,6 +127,12 @@ def linkshortening_messaging_service_domain_association( ) 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 b6ac290064..349d7ba4f3 100644 --- a/twilio/rest/messaging/v1/brand_registration/__init__.py +++ b/twilio/rest/messaging/v1/brand_registration/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -46,7 +47,9 @@ class Status(object): APPROVED = "APPROVED" FAILED = "FAILED" IN_REVIEW = "IN_REVIEW" - DELETED = "DELETED" + DELETION_PENDING = "DELETION_PENDING" + DELETION_FAILED = "DELETION_FAILED" + SUSPENDED = "SUSPENDED" """ :ivar sid: The unique string to identify Brand Registration. @@ -120,6 +123,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[BrandRegistrationContext] = None @property @@ -155,6 +159,24 @@ async def fetch_async(self) -> "BrandRegistrationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BrandRegistrationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BrandRegistrationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self) -> "BrandRegistrationInstance": """ Update the BrandRegistrationInstance @@ -173,6 +195,24 @@ async def update_async(self) -> "BrandRegistrationInstance": """ return await self._proxy.update_async() + def update_with_http_info(self) -> ApiResponse: + """ + Update the BrandRegistrationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info() + + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the BrandRegistrationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async() + @property def brand_registration_otps(self) -> BrandRegistrationOtpList: """ @@ -217,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 @@ -224,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: """ @@ -243,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: """ @@ -262,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: """ @@ -281,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: @@ -335,6 +473,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BrandRegistrationInstance: :param payload: Payload response from the API """ + return BrandRegistrationInstance(self._version, payload) def __repr__(self) -> str: @@ -359,24 +498,19 @@ def __init__(self, version: Version): self._uri = "/a2p/BrandRegistrations" - def create( + def _create( self, customer_profile_bundle_sid: str, a2p_profile_bundle_sid: str, brand_type: Union[str, object] = values.unset, mock: Union[bool, object] = values.unset, skip_automatic_sec_vet: Union[bool, object] = values.unset, - ) -> BrandRegistrationInstance: + ) -> tuple: """ - Create the BrandRegistrationInstance - - :param customer_profile_bundle_sid: Customer Profile Bundle Sid. - :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. - :param brand_type: Type of brand being created. One of: \\\"STANDARD\\\", \\\"SOLE_PROPRIETOR\\\". SOLE_PROPRIETOR is for low volume, SOLE_PROPRIETOR use cases. STANDARD is for all other use cases. - :param mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. - :param skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + Internal helper for create operation - :returns: The created BrandRegistrationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -392,13 +526,15 @@ def create( ) headers = values.of({"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 BrandRegistrationInstance(self._version, payload) - - async def create_async( + def create( self, customer_profile_bundle_sid: str, a2p_profile_bundle_sid: str, @@ -407,7 +543,7 @@ async def create_async( skip_automatic_sec_vet: Union[bool, object] = values.unset, ) -> BrandRegistrationInstance: """ - Asynchronously create the BrandRegistrationInstance + Create the BrandRegistrationInstance :param customer_profile_bundle_sid: Customer Profile Bundle Sid. :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. @@ -417,6 +553,58 @@ async def create_async( :returns: The created BrandRegistrationInstance """ + payload, _, _ = self._create( + customer_profile_bundle_sid=customer_profile_bundle_sid, + a2p_profile_bundle_sid=a2p_profile_bundle_sid, + brand_type=brand_type, + mock=mock, + skip_automatic_sec_vet=skip_automatic_sec_vet, + ) + return BrandRegistrationInstance(self._version, payload) + + def create_with_http_info( + self, + customer_profile_bundle_sid: str, + a2p_profile_bundle_sid: str, + brand_type: Union[str, object] = values.unset, + mock: Union[bool, object] = values.unset, + skip_automatic_sec_vet: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the BrandRegistrationInstance and return response metadata + + :param customer_profile_bundle_sid: Customer Profile Bundle Sid. + :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. + :param brand_type: Type of brand being created. One of: \\\"STANDARD\\\", \\\"SOLE_PROPRIETOR\\\". SOLE_PROPRIETOR is for low volume, SOLE_PROPRIETOR use cases. STANDARD is for all other use cases. + :param mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. + :param skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + customer_profile_bundle_sid=customer_profile_bundle_sid, + a2p_profile_bundle_sid=a2p_profile_bundle_sid, + brand_type=brand_type, + mock=mock, + skip_automatic_sec_vet=skip_automatic_sec_vet, + ) + instance = BrandRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + customer_profile_bundle_sid: str, + a2p_profile_bundle_sid: str, + brand_type: Union[str, object] = values.unset, + mock: Union[bool, object] = values.unset, + skip_automatic_sec_vet: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -431,12 +619,71 @@ async def create_async( ) headers = values.of({"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, + customer_profile_bundle_sid: str, + a2p_profile_bundle_sid: str, + brand_type: Union[str, object] = values.unset, + mock: Union[bool, object] = values.unset, + skip_automatic_sec_vet: Union[bool, object] = values.unset, + ) -> BrandRegistrationInstance: + """ + Asynchronously create the BrandRegistrationInstance + + :param customer_profile_bundle_sid: Customer Profile Bundle Sid. + :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. + :param brand_type: Type of brand being created. One of: \\\"STANDARD\\\", \\\"SOLE_PROPRIETOR\\\". SOLE_PROPRIETOR is for low volume, SOLE_PROPRIETOR use cases. STANDARD is for all other use cases. + :param mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. + :param skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + + :returns: The created BrandRegistrationInstance + """ + payload, _, _ = await self._create_async( + customer_profile_bundle_sid=customer_profile_bundle_sid, + a2p_profile_bundle_sid=a2p_profile_bundle_sid, + brand_type=brand_type, + mock=mock, + skip_automatic_sec_vet=skip_automatic_sec_vet, + ) return BrandRegistrationInstance(self._version, payload) + async def create_with_http_info_async( + self, + customer_profile_bundle_sid: str, + a2p_profile_bundle_sid: str, + brand_type: Union[str, object] = values.unset, + mock: Union[bool, object] = values.unset, + skip_automatic_sec_vet: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the BrandRegistrationInstance and return response metadata + + :param customer_profile_bundle_sid: Customer Profile Bundle Sid. + :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. + :param brand_type: Type of brand being created. One of: \\\"STANDARD\\\", \\\"SOLE_PROPRIETOR\\\". SOLE_PROPRIETOR is for low volume, SOLE_PROPRIETOR use cases. STANDARD is for all other use cases. + :param mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. + :param skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + customer_profile_bundle_sid=customer_profile_bundle_sid, + a2p_profile_bundle_sid=a2p_profile_bundle_sid, + brand_type=brand_type, + mock=mock, + skip_automatic_sec_vet=skip_automatic_sec_vet, + ) + instance = BrandRegistrationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -487,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, @@ -506,6 +803,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -532,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( @@ -540,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, @@ -564,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( @@ -591,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 74631cea78..0ac2f302c5 100644 --- a/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py +++ b/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,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,37 +94,73 @@ def create(self) -> BrandRegistrationOtpInstance: :returns: The created BrandRegistrationOtpInstance """ + payload, _, _ = self._create() + return BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], + ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + def create_with_http_info(self) -> ApiResponse: + """ + Create the BrandRegistrationOtpInstance and return response metadata - payload = self._version.create(method="POST", uri=self._uri, headers=headers) - return BrandRegistrationOtpInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = BrandRegistrationOtpInstance( self._version, payload, brand_registration_sid=self._solution["brand_registration_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - async def create_async(self) -> BrandRegistrationOtpInstance: + async def _create_async(self) -> tuple: """ - Asynchronously create the BrandRegistrationOtpInstance - + Internal async helper for create operation - :returns: The created BrandRegistrationOtpInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( + 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: + """ + Asynchronously create the BrandRegistrationOtpInstance + + + :returns: The created BrandRegistrationOtpInstance + """ + payload, _, _ = await self._create_async() return BrandRegistrationOtpInstance( self._version, payload, brand_registration_sid=self._solution["brand_registration_sid"], ) + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the BrandRegistrationOtpInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/brand_registration/brand_vetting.py b/twilio/rest/messaging/v1/brand_registration/brand_vetting.py index 37fe4ed8d4..9cd9243470 100644 --- a/twilio/rest/messaging/v1/brand_registration/brand_vetting.py +++ b/twilio/rest/messaging/v1/brand_registration/brand_vetting.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -26,6 +27,7 @@ class BrandVettingInstance(InstanceResource): class VettingProvider(object): CAMPAIGN_VERIFY = "campaign-verify" + AEGIS = "aegis" """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the vetting record. @@ -70,6 +72,7 @@ def __init__( "brand_sid": brand_sid, "brand_vetting_sid": brand_vetting_sid or self.brand_vetting_sid, } + self._context: Optional[BrandVettingContext] = None @property @@ -106,6 +109,24 @@ async def fetch_async(self) -> "BrandVettingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BrandVettingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BrandVettingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -139,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 @@ -146,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: """ @@ -166,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: """ @@ -197,6 +272,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BrandVettingInstance: :param payload: Payload response from the API """ + return BrandVettingInstance( self._version, payload, brand_sid=self._solution["brand_sid"] ) @@ -230,18 +306,16 @@ def __init__(self, version: Version, brand_sid: str): **self._solution ) - def create( + def _create( self, vetting_provider: "BrandVettingInstance.VettingProvider", vetting_id: Union[str, object] = values.unset, - ) -> BrandVettingInstance: + ) -> tuple: """ - Create the BrandVettingInstance - - :param vetting_provider: - :param vetting_id: The unique ID of the vetting + Internal helper for create operation - :returns: The created BrandVettingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -252,26 +326,65 @@ def create( ) headers = values.of({"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, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> BrandVettingInstance: + """ + Create the BrandVettingInstance + + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The created BrandVettingInstance + """ + payload, _, _ = self._create( + vetting_provider=vetting_provider, vetting_id=vetting_id + ) return BrandVettingInstance( self._version, payload, brand_sid=self._solution["brand_sid"] ) - async def create_async( + def create_with_http_info( self, vetting_provider: "BrandVettingInstance.VettingProvider", vetting_id: Union[str, object] = values.unset, - ) -> BrandVettingInstance: + ) -> ApiResponse: """ - Asynchronously create the BrandVettingInstance + Create the BrandVettingInstance and return response metadata :param vetting_provider: :param vetting_id: The unique ID of the vetting - :returns: The created BrandVettingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + vetting_provider=vetting_provider, vetting_id=vetting_id + ) + instance = BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -282,14 +395,55 @@ async def create_async( ) headers = values.of({"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, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> BrandVettingInstance: + """ + Asynchronously create the BrandVettingInstance + + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The created BrandVettingInstance + """ + payload, _, _ = await self._create_async( + vetting_provider=vetting_provider, vetting_id=vetting_id + ) return BrandVettingInstance( self._version, payload, brand_sid=self._solution["brand_sid"] ) + async def create_with_http_info_async( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the BrandVettingInstance and return response metadata + + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + vetting_provider=vetting_provider, vetting_id=vetting_id + ) + instance = BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, vetting_provider: Union[ @@ -352,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[ @@ -375,6 +589,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( vetting_provider=vetting_provider, @@ -406,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( @@ -415,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[ @@ -444,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, @@ -476,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: """ @@ -491,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: """ @@ -503,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 6616d87df5..ddcbff4af8 100644 --- a/twilio/rest/messaging/v1/deactivations.py +++ b/twilio/rest/messaging/v1/deactivations.py @@ -15,6 +15,7 @@ from datetime import date from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,6 +76,34 @@ async def fetch_async( date=date, ) + def fetch_with_http_info( + self, date: Union[date, object] = values.unset + ) -> ApiResponse: + """ + Fetch the DeactivationsInstance with HTTP info + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + date=date, + ) + + async def fetch_with_http_info_async( + self, date: Union[date, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeactivationsInstance with HTTP info + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + date=date, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -97,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 - - :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. + Internal helper for fetch operation - :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 - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + 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 diff --git a/twilio/rest/messaging/v1/domain_certs.py b/twilio/rest/messaging/v1/domain_certs.py index 3acc8a18ff..76fea05f18 100644 --- a/twilio/rest/messaging/v1/domain_certs.py +++ b/twilio/rest/messaging/v1/domain_certs.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "domain_sid": domain_sid or self.domain_sid, } + self._context: Optional[DomainCertsContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "DomainCertsInstance": """ Fetch the DomainCertsInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "DomainCertsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainCertsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, tls_cert: str) -> "DomainCertsInstance": """ Update the DomainCertsInstance @@ -138,6 +176,30 @@ async def update_async(self, tls_cert: str) -> "DomainCertsInstance": tls_cert=tls_cert, ) + def update_with_http_info(self, tls_cert: str) -> ApiResponse: + """ + Update the DomainCertsInstance with HTTP info + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + tls_cert=tls_cert, + ) + + async def update_with_http_info_async(self, tls_cert: str) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainCertsInstance with HTTP info + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + tls_cert=tls_cert, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -167,6 +229,20 @@ def __init__(self, version: Version, domain_sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the DomainCertsInstance @@ -174,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: @@ -186,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: @@ -198,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: """ @@ -217,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" - 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, tls_cert: str) -> DomainCertsInstance: + """ + Asynchronous coroutine to update the DomainCertsInstance + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: The updated DomainCertsInstance + """ + payload, _, _ = await self._update_async(tls_cert=tls_cert) return DomainCertsInstance( self._version, payload, domain_sid=self._solution["domain_sid"] ) + async def update_with_http_info_async(self, tls_cert: str) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainCertsInstance and return response metadata + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(tls_cert=tls_cert) + instance = DomainCertsInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/domain_config.py b/twilio/rest/messaging/v1/domain_config.py index 25d69342d0..1fa8341f21 100644 --- a/twilio/rest/messaging/v1/domain_config.py +++ b/twilio/rest/messaging/v1/domain_config.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -59,6 +60,7 @@ def __init__( self._solution = { "domain_sid": domain_sid or self.domain_sid, } + self._context: Optional[DomainConfigContext] = None @property @@ -94,6 +96,24 @@ async def fetch_async(self) -> "DomainConfigInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainConfigInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainConfigInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, fallback_url: Union[str, object] = values.unset, @@ -142,6 +162,54 @@ async def update_async( disable_https=disable_https, ) + def update_with_http_info( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the DomainConfigInstance with HTTP info + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + + async def update_with_http_info_async( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DomainConfigInstance with HTTP info + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -171,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 @@ -178,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: """ @@ -197,17 +307,59 @@ 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, @@ -226,6 +378,58 @@ def update( :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( { "FallbackUrl": fallback_url, @@ -234,15 +438,14 @@ def update( "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( @@ -262,24 +465,43 @@ async def update_async( :returns: The updated DomainConfigInstance """ - data = values.of( - { - "FallbackUrl": fallback_url, - "CallbackUrl": callback_url, - "ContinueOnFailure": serialize.boolean_to_string(continue_on_failure), - "DisableHttps": serialize.boolean_to_string(disable_https), - } + 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: """ diff --git a/twilio/rest/messaging/v1/domain_config_messaging_service.py b/twilio/rest/messaging/v1/domain_config_messaging_service.py index 178ebd544e..b8291f2585 100644 --- a/twilio/rest/messaging/v1/domain_config_messaging_service.py +++ b/twilio/rest/messaging/v1/domain_config_messaging_service.py @@ -14,7 +14,8 @@ 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 @@ -60,6 +61,7 @@ def __init__( "messaging_service_sid": messaging_service_sid or self.messaging_service_sid, } + self._context: Optional[DomainConfigMessagingServiceContext] = None @property @@ -95,6 +97,24 @@ async def fetch_async(self) -> "DomainConfigMessagingServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainConfigMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DomainConfigMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -126,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 @@ -133,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: """ @@ -152,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: """ 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 88262f978d..dd16e80319 100644 --- a/twilio/rest/messaging/v1/external_campaign.py +++ b/twilio/rest/messaging/v1/external_campaign.py @@ -13,8 +13,9 @@ """ from datetime import datetime -from typing import Any, Dict, Optional -from twilio.base import deserialize, values +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -64,58 +65,156 @@ def __init__(self, version: Version): self._uri = "/Services/PreregisteredUsa2p" - def create( - self, campaign_id: str, messaging_service_sid: str - ) -> ExternalCampaignInstance: + def _create( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> tuple: """ - Create the ExternalCampaignInstance + Internal helper for create operation - :param campaign_id: ID of the preregistered campaign. - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. - - :returns: The created ExternalCampaignInstance + 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( + 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 ExternalCampaignInstance(self._version, payload) - - async def create_async( - self, campaign_id: str, messaging_service_sid: str + def create( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, ) -> ExternalCampaignInstance: """ - Asynchronously create the ExternalCampaignInstance + Create the ExternalCampaignInstance :param campaign_id: ID of the preregistered campaign. :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :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 = 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, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> ExternalCampaignInstance: + """ + Asynchronously create the ExternalCampaignInstance + + :param campaign_id: ID of the preregistered campaign. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :param cnp_migration: Customers should use this flag during the ERC registration process to indicate to Twilio that the campaign being registered is undergoing CNP migration. It is important for the user to first trigger the CNP migration process for said campaign in their CSP portal and have Twilio accept the sharing request, before making this api call. + + :returns: The created ExternalCampaignInstance + """ + payload, _, _ = await self._create_async( + campaign_id=campaign_id, + messaging_service_sid=messaging_service_sid, + cnp_migration=cnp_migration, + ) return ExternalCampaignInstance(self._version, payload) + async def create_with_http_info_async( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ExternalCampaignInstance and return response metadata + + :param campaign_id: ID of the preregistered campaign. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :param cnp_migration: Customers should use this flag during the ERC registration process to indicate to Twilio that the campaign being registered is undergoing CNP migration. It is important for the user to first trigger the CNP migration process for said campaign in their CSP portal and have Twilio accept the sharing request, before making this api call. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + campaign_id=campaign_id, + messaging_service_sid=messaging_service_sid, + cnp_migration=cnp_migration, + ) + instance = ExternalCampaignInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/linkshortening_messaging_service.py b/twilio/rest/messaging/v1/linkshortening_messaging_service.py index 94ebfa6173..9549b84828 100644 --- a/twilio/rest/messaging/v1/linkshortening_messaging_service.py +++ b/twilio/rest/messaging/v1/linkshortening_messaging_service.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -45,6 +46,7 @@ def __init__( "messaging_service_sid": messaging_service_sid or self.messaging_service_sid, } + self._context: Optional[LinkshorteningMessagingServiceContext] = None @property @@ -81,6 +83,24 @@ async def create_async(self) -> "LinkshorteningMessagingServiceInstance": """ return await self._proxy.create_async() + def create_with_http_info(self) -> ApiResponse: + """ + Create the LinkshorteningMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info() + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the LinkshorteningMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async() + def delete(self) -> bool: """ Deletes the LinkshorteningMessagingServiceInstance @@ -99,6 +119,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the LinkshorteningMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the LinkshorteningMessagingServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -132,6 +170,23 @@ def __init__(self, version: Version, domain_sid: str, messaging_service_sid: str **self._solution ) + def _create(self) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create(self) -> LinkshorteningMessagingServiceInstance: """ Create the LinkshorteningMessagingServiceInstance @@ -139,16 +194,46 @@ def create(self) -> LinkshorteningMessagingServiceInstance: :returns: The created LinkshorteningMessagingServiceInstance """ - data = values.of({}) + payload, _, _ = self._create() + return LinkshorteningMessagingServiceInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the LinkshorteningMessagingServiceInstance and return response metadata - payload = self._version.create(method="POST", uri=self._uri, data=data) - return LinkshorteningMessagingServiceInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = LinkshorteningMessagingServiceInstance( self._version, payload, domain_sid=self._solution["domain_sid"], messaging_service_sid=self._solution["messaging_service_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) async def create_async(self) -> LinkshorteningMessagingServiceInstance: """ @@ -157,18 +242,43 @@ async def create_async(self) -> LinkshorteningMessagingServiceInstance: :returns: The created LinkshorteningMessagingServiceInstance """ - data = values.of({}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data + payload, _, _ = await self._create_async() + return LinkshorteningMessagingServiceInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], ) - return LinkshorteningMessagingServiceInstance( + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the LinkshorteningMessagingServiceInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = LinkshorteningMessagingServiceInstance( self._version, payload, domain_sid=self._solution["domain_sid"], messaging_service_sid=self._solution["messaging_service_sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) def delete(self) -> bool: """ @@ -177,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: @@ -189,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: """ diff --git a/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py b/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py index a1252d2b35..1d88d07d0f 100644 --- a/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py +++ b/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py @@ -13,6 +13,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 @@ -42,6 +44,7 @@ def __init__( "messaging_service_sid": messaging_service_sid or self.messaging_service_sid, } + self._context: Optional[ LinkshorteningMessagingServiceDomainAssociationContext ] = None @@ -81,6 +84,24 @@ async def fetch_async( """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the LinkshorteningMessagingServiceDomainAssociationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -114,6 +135,22 @@ def __init__(self, version: Version, messaging_service_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) -> LinkshorteningMessagingServiceDomainAssociationInstance: """ Fetch the LinkshorteningMessagingServiceDomainAssociationInstance @@ -121,17 +158,43 @@ def fetch(self) -> LinkshorteningMessagingServiceDomainAssociationInstance: :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return LinkshorteningMessagingServiceDomainAssociationInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], ) - return LinkshorteningMessagingServiceDomainAssociationInstance( + 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, @@ -142,17 +205,27 @@ async def fetch_async( :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return LinkshorteningMessagingServiceDomainAssociationInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], ) - return LinkshorteningMessagingServiceDomainAssociationInstance( + 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: """ 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 0fbb3dd10b..d7da850830 100644 --- a/twilio/rest/messaging/v1/service/__init__.py +++ b/twilio/rest/messaging/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -22,6 +23,9 @@ from twilio.base.page import Page from twilio.rest.messaging.v1.service.alpha_sender import AlphaSenderList from twilio.rest.messaging.v1.service.channel_sender import ChannelSenderList +from twilio.rest.messaging.v1.service.destination_alpha_sender import ( + DestinationAlphaSenderList, +) from twilio.rest.messaging.v1.service.phone_number import PhoneNumberList from twilio.rest.messaging.v1.service.short_code import ShortCodeList from twilio.rest.messaging.v1.service.us_app_to_person import UsAppToPersonList @@ -55,7 +59,7 @@ class ScanMessageContent(object): :ivar fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. :ivar area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. :ivar synchronous_validation: Reserved. - :ivar validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. + :ivar validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. :ivar url: The absolute URL of the Service resource. :ivar links: The absolute URLs of related resources. :ivar usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. @@ -111,6 +115,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -146,6 +151,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -164,6 +187,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -200,7 +241,7 @@ def update( :param scan_message_content: :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. - :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. :param synchronous_validation: Reserved. :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. @@ -262,7 +303,7 @@ async def update_async( :param scan_message_content: :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. - :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. :param synchronous_validation: Reserved. :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. @@ -288,6 +329,130 @@ async def update_async( use_inbound_webhook_on_number=use_inbound_webhook_on_number, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + @property def alpha_senders(self) -> AlphaSenderList: """ @@ -302,6 +467,13 @@ def channel_senders(self) -> ChannelSenderList: """ return self._proxy.channel_senders + @property + def destination_alpha_senders(self) -> DestinationAlphaSenderList: + """ + Access the destination_alpha_senders + """ + return self._proxy.destination_alpha_senders + @property def phone_numbers(self) -> PhoneNumberList: """ @@ -359,11 +531,26 @@ def __init__(self, version: Version, sid: str): self._alpha_senders: Optional[AlphaSenderList] = None self._channel_senders: Optional[ChannelSenderList] = None + self._destination_alpha_senders: Optional[DestinationAlphaSenderList] = None self._phone_numbers: Optional[PhoneNumberList] = None self._short_codes: Optional[ShortCodeList] = None self._us_app_to_person: Optional[UsAppToPersonList] = None self._us_app_to_person_usecases: Optional[UsAppToPersonUsecaseList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ServiceInstance @@ -371,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: @@ -383,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: @@ -395,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: """ @@ -414,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, @@ -446,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/messaging/services#sticky-sender) on the Service instance. - :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. - :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. - :param scan_message_content: - :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. - :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. - :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. - :param synchronous_validation: Reserved. - :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. - :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + Internal helper for update operation - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -495,16 +749,17 @@ def update( ), } ) + 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, @@ -526,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. @@ -540,47 +795,287 @@ async def update_async( :param scan_message_content: :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. - :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. + :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 """ - data = values.of( - { - "FriendlyName": friendly_name, - "InboundRequestUrl": inbound_request_url, - "InboundMethod": inbound_method, - "FallbackUrl": fallback_url, - "FallbackMethod": fallback_method, - "StatusCallback": status_callback, - "StickySender": serialize.boolean_to_string(sticky_sender), - "MmsConverter": serialize.boolean_to_string(mms_converter), - "SmartEncoding": serialize.boolean_to_string(smart_encoding), - "ScanMessageContent": scan_message_content, - "FallbackToLongCode": serialize.boolean_to_string( - fallback_to_long_code - ), - "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), - "ValidityPeriod": validity_period, - "SynchronousValidation": serialize.boolean_to_string( - synchronous_validation - ), - "Usecase": usecase, - "UseInboundWebhookOnNumber": serialize.boolean_to_string( - use_inbound_webhook_on_number - ), - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + 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"]) + + 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: @@ -606,6 +1101,18 @@ def channel_senders(self) -> ChannelSenderList: ) return self._channel_senders + @property + def destination_alpha_senders(self) -> DestinationAlphaSenderList: + """ + Access the destination_alpha_senders + """ + if self._destination_alpha_senders is None: + self._destination_alpha_senders = DestinationAlphaSenderList( + self._version, + self._solution["sid"], + ) + return self._destination_alpha_senders + @property def phone_numbers(self) -> PhoneNumberList: """ @@ -672,6 +1179,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -696,7 +1204,198 @@ def __init__(self, version: Version): self._uri = "/Services" - def create( + def _create( + self, + friendly_name: str, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "InboundRequestUrl": inbound_request_url, + "InboundMethod": inbound_method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StickySender": serialize.boolean_to_string(sticky_sender), + "MmsConverter": serialize.boolean_to_string(mms_converter), + "SmartEncoding": serialize.boolean_to_string(smart_encoding), + "ScanMessageContent": scan_message_content, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), + "ValidityPeriod": validity_period, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), + "Usecase": usecase, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( self, friendly_name: str, inbound_request_url: Union[str, object] = values.unset, @@ -716,28 +1415,12 @@ def create( synchronous_validation: Union[bool, object] = values.unset, usecase: Union[str, object] = values.unset, use_inbound_webhook_on_number: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Create the ServiceInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. - :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. - :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. - :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. - :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. - :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. - :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. - :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. - :param scan_message_content: - :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. - :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. - :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. - :param synchronous_validation: Reserved. - :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. - :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + Internal async helper for create operation - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -768,12 +1451,14 @@ def create( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( + 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 ) - return ServiceInstance(self._version, payload) - async def create_async( self, friendly_name: str, @@ -810,47 +1495,96 @@ async def create_async( :param scan_message_content: :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. - :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `36,000`. Default value is `36,000`. :param synchronous_validation: Reserved. :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. :returns: The created ServiceInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "InboundRequestUrl": inbound_request_url, - "InboundMethod": inbound_method, - "FallbackUrl": fallback_url, - "FallbackMethod": fallback_method, - "StatusCallback": status_callback, - "StickySender": serialize.boolean_to_string(sticky_sender), - "MmsConverter": serialize.boolean_to_string(mms_converter), - "SmartEncoding": serialize.boolean_to_string(smart_encoding), - "ScanMessageContent": scan_message_content, - "FallbackToLongCode": serialize.boolean_to_string( - fallback_to_long_code - ), - "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), - "ValidityPeriod": validity_period, - "SynchronousValidation": serialize.boolean_to_string( - synchronous_validation - ), - "Usecase": usecase, - "UseInboundWebhookOnNumber": serialize.boolean_to_string( - use_inbound_webhook_on_number - ), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + return ServiceInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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, @@ -902,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, @@ -921,6 +1705,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -947,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( @@ -955,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, @@ -979,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( @@ -1006,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 0173c98099..2d91b12ebd 100644 --- a/twilio/rest/messaging/v1/service/alpha_sender.py +++ b/twilio/rest/messaging/v1/service/alpha_sender.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[AlphaSenderContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AlphaSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AlphaSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AlphaSenderInstance": """ Fetch the AlphaSenderInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "AlphaSenderInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AlphaSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AlphaSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -145,6 +183,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AlphaSenderInstance @@ -152,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: @@ -164,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: @@ -176,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: """ @@ -196,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: """ @@ -227,6 +363,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AlphaSenderInstance: :param payload: Payload response from the API """ + return AlphaSenderInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -258,13 +395,12 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/AlphaSenders".format(**self._solution) - def create(self, alpha_sender: str) -> AlphaSenderInstance: + def _create(self, alpha_sender: str) -> tuple: """ - Create the AlphaSenderInstance - - :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( @@ -274,21 +410,47 @@ def create(self, alpha_sender: str) -> AlphaSenderInstance: ) headers = values.of({"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, 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( @@ -298,14 +460,43 @@ async def create_async(self, alpha_sender: str) -> AlphaSenderInstance: ) headers = values.of({"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, 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, @@ -356,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, @@ -375,6 +616,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -401,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( @@ -409,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, @@ -433,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, @@ -460,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: """ @@ -475,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: """ @@ -487,7 +860,7 @@ async def get_page_async(self, target_url: str) -> AlphaSenderPage: :returns: Page of AlphaSenderInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return AlphaSenderPage(self._version, response, self._solution) + return AlphaSenderPage(self._version, response, solution=self._solution) def get(self, sid: str) -> AlphaSenderContext: """ diff --git a/twilio/rest/messaging/v1/service/channel_sender.py b/twilio/rest/messaging/v1/service/channel_sender.py index a8de3d0cf6..37a8f4d9a5 100644 --- a/twilio/rest/messaging/v1/service/channel_sender.py +++ b/twilio/rest/messaging/v1/service/channel_sender.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def __init__( "messaging_service_sid": messaging_service_sid, "sid": sid or self.sid, } + self._context: Optional[ChannelSenderContext] = None @property @@ -80,6 +82,42 @@ def _proxy(self) -> "ChannelSenderContext": ) 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 @@ -98,6 +136,24 @@ async def fetch_async(self) -> "ChannelSenderInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChannelSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -129,6 +185,90 @@ def __init__(self, version: Version, messaging_service_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the ChannelSenderInstance + + + :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 @@ -136,18 +276,45 @@ def fetch(self) -> ChannelSenderInstance: :returns: The fetched ChannelSenderInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], ) - return ChannelSenderInstance( + 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: """ @@ -156,18 +323,29 @@ async def fetch_async(self) -> ChannelSenderInstance: :returns: The fetched ChannelSenderInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], ) - return ChannelSenderInstance( + 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: """ @@ -187,6 +365,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChannelSenderInstance: :param payload: Payload response from the API """ + return ChannelSenderInstance( self._version, payload, @@ -222,6 +401,114 @@ def __init__(self, version: Version, messaging_service_sid: str): **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, @@ -272,6 +559,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ChannelSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ChannelSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -291,6 +628,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -317,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( @@ -325,6 +664,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ChannelSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ChannelSenderInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -349,8 +738,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ChannelSenderPage(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 ChannelSenderPage(self._version, response, solution=self._solution) async def page_async( self, @@ -376,10 +771,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 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 + ) ) - return ChannelSenderPage(self._version, response, self._solution) + 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: """ @@ -391,7 +860,7 @@ def get_page(self, target_url: str) -> ChannelSenderPage: :returns: Page of ChannelSenderInstance """ response = self._version.domain.twilio.request("GET", target_url) - return ChannelSenderPage(self._version, response, self._solution) + return ChannelSenderPage(self._version, response, solution=self._solution) async def get_page_async(self, target_url: str) -> ChannelSenderPage: """ @@ -403,7 +872,7 @@ async def get_page_async(self, target_url: str) -> ChannelSenderPage: :returns: Page of ChannelSenderInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ChannelSenderPage(self._version, response, self._solution) + return ChannelSenderPage(self._version, response, solution=self._solution) def get(self, sid: str) -> ChannelSenderContext: """ diff --git a/twilio/rest/messaging/v1/service/destination_alpha_sender.py b/twilio/rest/messaging/v1/service/destination_alpha_sender.py new file mode 100644 index 0000000000..4b8194b368 --- /dev/null +++ b/twilio/rest/messaging/v1/service/destination_alpha_sender.py @@ -0,0 +1,969 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DestinationAlphaSenderInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AlphaSender resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AlphaSender resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar alpha_sender: The Alphanumeric Sender ID string. + :ivar capabilities: An array of values that describe whether the number can receive calls or messages. Can be: `SMS`. + :ivar url: The absolute URL of the AlphaSender resource. + :ivar iso_country_code: The Two Character ISO Country Code the Alphanumeric Sender ID will be used for. For Default Alpha Senders that work across countries, this value will be an empty string + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.alpha_sender: Optional[str] = payload.get("alpha_sender") + self.capabilities: Optional[List[str]] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + self.iso_country_code: Optional[str] = payload.get("iso_country_code") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[DestinationAlphaSenderContext] = None + + @property + def _proxy(self) -> "DestinationAlphaSenderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DestinationAlphaSenderContext for this DestinationAlphaSenderInstance + """ + if self._context is None: + self._context = DestinationAlphaSenderContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DestinationAlphaSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DestinationAlphaSenderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch(self) -> "DestinationAlphaSenderInstance": + """ + Fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DestinationAlphaSenderInstance": + """ + Asynchronous coroutine to fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DestinationAlphaSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DestinationAlphaSenderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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 10d30ab7fa..9992fd0102 100644 --- a/twilio/rest/messaging/v1/service/phone_number.py +++ b/twilio/rest/messaging/v1/service/phone_number.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[PhoneNumberContext] = None @property @@ -98,6 +100,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "PhoneNumberInstance": """ Fetch the PhoneNumberInstance @@ -116,6 +136,24 @@ async def fetch_async(self) -> "PhoneNumberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -147,6 +185,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PhoneNumberInstance @@ -154,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: @@ -166,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: @@ -178,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: """ @@ -198,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: """ @@ -229,6 +365,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: :param payload: Payload response from the API """ + return PhoneNumberInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -260,13 +397,12 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/PhoneNumbers".format(**self._solution) - def create(self, phone_number_sid: str) -> PhoneNumberInstance: + def _create(self, phone_number_sid: str) -> tuple: """ - Create the PhoneNumberInstance - - :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( @@ -276,21 +412,47 @@ def create(self, phone_number_sid: str) -> PhoneNumberInstance: ) headers = values.of({"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, 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( @@ -300,14 +462,43 @@ async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: ) headers = values.of({"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, 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, @@ -358,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, @@ -377,6 +618,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -403,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( @@ -411,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, @@ -435,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, @@ -462,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: """ @@ -477,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: """ @@ -489,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 c8f1b3e3c8..f1e7039dfc 100644 --- a/twilio/rest/messaging/v1/service/short_code.py +++ b/twilio/rest/messaging/v1/service/short_code.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[ShortCodeContext] = None @property @@ -98,6 +100,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ShortCodeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ShortCodeInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ShortCodeInstance": """ Fetch the ShortCodeInstance @@ -116,6 +136,24 @@ async def fetch_async(self) -> "ShortCodeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ShortCodeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ShortCodeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -145,6 +183,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/ShortCodes/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ShortCodeInstance @@ -152,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: @@ -164,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: @@ -176,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: """ @@ -196,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: """ @@ -227,6 +363,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: :param payload: Payload response from the API """ + return ShortCodeInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -258,13 +395,12 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/ShortCodes".format(**self._solution) - def create(self, short_code_sid: str) -> ShortCodeInstance: + def _create(self, short_code_sid: str) -> tuple: """ - Create the ShortCodeInstance - - :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( @@ -274,21 +410,47 @@ def create(self, short_code_sid: str) -> ShortCodeInstance: ) headers = values.of({"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, 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( @@ -298,14 +460,43 @@ async def create_async(self, short_code_sid: str) -> ShortCodeInstance: ) headers = values.of({"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, 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, @@ -356,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, @@ -375,6 +616,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -401,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( @@ -409,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, @@ -433,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, @@ -460,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: """ @@ -475,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: """ @@ -487,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 ad31c6a4b7..ba3bfdc125 100644 --- a/twilio/rest/messaging/v1/service/us_app_to_person.py +++ b/twilio/rest/messaging/v1/service/us_app_to_person.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -52,6 +53,8 @@ class UsAppToPersonInstance(InstanceResource): :ivar url: The absolute URL of the US App to Person resource. :ivar mock: A boolean that specifies whether campaign is a mock or not. Mock campaigns will be automatically created if using a mock brand. Mock campaigns should only be used for testing purposes. :ivar errors: Details indicating why a campaign registration failed. These errors can indicate one or more fields that were incorrect or did not meet review requirements. + :ivar privacy_policy_url: The URL of the privacy policy for the campaign. + :ivar terms_and_conditions_url: The URL of the terms and conditions for the campaign. """ def __init__( @@ -101,11 +104,16 @@ def __init__( self.url: Optional[str] = payload.get("url") self.mock: Optional[bool] = payload.get("mock") self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + self.privacy_policy_url: Optional[str] = payload.get("privacy_policy_url") + self.terms_and_conditions_url: Optional[str] = payload.get( + "terms_and_conditions_url" + ) self._solution = { "messaging_service_sid": messaging_service_sid, "sid": sid or self.sid, } + self._context: Optional[UsAppToPersonContext] = None @property @@ -142,23 +150,79 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() - def fetch(self) -> "UsAppToPersonInstance": + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the UsAppToPersonInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UsAppToPersonInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + + def fetch( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> "UsAppToPersonInstance": """ Fetch the UsAppToPersonInstance + :param x_twilio_api_version: The version of the Messaging API to use for this request :returns: The fetched UsAppToPersonInstance """ - return self._proxy.fetch() + return self._proxy.fetch( + x_twilio_api_version=x_twilio_api_version, + ) - async def fetch_async(self) -> "UsAppToPersonInstance": + async def fetch_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> "UsAppToPersonInstance": """ Asynchronous coroutine to fetch the UsAppToPersonInstance + :param x_twilio_api_version: The version of the Messaging API to use for this request :returns: The fetched UsAppToPersonInstance """ - return await self._proxy.fetch_async() + return await self._proxy.fetch_async( + x_twilio_api_version=x_twilio_api_version, + ) + + def fetch_with_http_info( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the UsAppToPersonInstance with HTTP info + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + x_twilio_api_version=x_twilio_api_version, + ) + + async def fetch_with_http_info_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UsAppToPersonInstance with HTTP info + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + x_twilio_api_version=x_twilio_api_version, + ) def update( self, @@ -169,6 +233,9 @@ def update( description: str, age_gated: bool, direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, ) -> "UsAppToPersonInstance": """ Update the UsAppToPersonInstance @@ -180,6 +247,9 @@ def update( :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. :returns: The updated UsAppToPersonInstance """ @@ -191,6 +261,9 @@ def update( description=description, age_gated=age_gated, direct_lending=direct_lending, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, ) async def update_async( @@ -202,6 +275,9 @@ async def update_async( description: str, age_gated: bool, direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, ) -> "UsAppToPersonInstance": """ Asynchronous coroutine to update the UsAppToPersonInstance @@ -213,6 +289,9 @@ async def update_async( :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. :returns: The updated UsAppToPersonInstance """ @@ -224,6 +303,93 @@ async def update_async( description=description, age_gated=age_gated, direct_lending=direct_lending, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + + def update_with_http_info( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the UsAppToPersonInstance with HTTP info + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + message_samples=message_samples, + message_flow=message_flow, + description=description, + age_gated=age_gated, + direct_lending=direct_lending, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + + async def update_with_http_info_async( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the UsAppToPersonInstance with HTTP info + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + message_samples=message_samples, + message_flow=message_flow, + description=description, + age_gated=age_gated, + direct_lending=direct_lending, + x_twilio_api_version=x_twilio_api_version, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, ) def __repr__(self) -> str: @@ -257,6 +423,20 @@ def __init__(self, version: Version, messaging_service_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the UsAppToPersonInstance @@ -264,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: @@ -276,44 +478,117 @@ 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 UsAppToPersonInstance 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, 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 + + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) - def fetch(self) -> UsAppToPersonInstance: + 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._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch(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"], ) - return UsAppToPersonInstance( + def fetch_with_http_info( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the UsAppToPersonInstance and return response metadata + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + x_twilio_api_version=x_twilio_api_version + ) + instance = UsAppToPersonInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - async def fetch_async(self) -> UsAppToPersonInstance: + async def _fetch_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + if not ( + x_twilio_api_version is values.unset + or (isinstance(x_twilio_api_version, str) and not x_twilio_api_version) + ): + headers["X-Twilio-Api-Version"] = x_twilio_api_version + + headers["Accept"] = "application/json" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) + + async def fetch_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> UsAppToPersonInstance: """ Asynchronous coroutine to fetch the UsAppToPersonInstance + :param x_twilio_api_version: The version of the Messaging API to use for this request :returns: The fetched UsAppToPersonInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async( + x_twilio_api_version=x_twilio_api_version ) - return UsAppToPersonInstance( self._version, payload, @@ -321,7 +596,28 @@ async def fetch_async(self) -> UsAppToPersonInstance: sid=self._solution["sid"], ) - def update( + async def fetch_with_http_info_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UsAppToPersonInstance and return response metadata + + :param x_twilio_api_version: The version of the Messaging API to use for this request + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + x_twilio_api_version=x_twilio_api_version + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( self, has_embedded_links: bool, has_embedded_phone: bool, @@ -330,20 +626,17 @@ def update( description: str, age_gated: bool, direct_lending: bool, - ) -> UsAppToPersonInstance: + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> tuple: """ - Update the UsAppToPersonInstance - - :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. - :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. - :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. - :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. - :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. - :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. - :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + Internal helper for update operation - :returns: The updated UsAppToPersonInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "HasEmbeddedLinks": serialize.boolean_to_string(has_embedded_links), @@ -353,23 +646,27 @@ def update( "Description": description, "AgeGated": serialize.boolean_to_string(age_gated), "DirectLending": serialize.boolean_to_string(direct_lending), + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return UsAppToPersonInstance( - self._version, - payload, - messaging_service_sid=self._solution["messaging_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, has_embedded_links: bool, has_embedded_phone: bool, @@ -378,9 +675,12 @@ async def update_async( description: str, age_gated: bool, direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, ) -> UsAppToPersonInstance: """ - Asynchronous coroutine to update the UsAppToPersonInstance + 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. @@ -389,27 +689,24 @@ async def update_async( :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. :returns: The updated UsAppToPersonInstance """ - 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), - } - ) - - payload = await self._version.update_async( - 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, @@ -417,46 +714,242 @@ 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, + 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: """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) + Update the UsAppToPersonInstance and return response metadata + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. -class UsAppToPersonPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> UsAppToPersonInstance: - """ - Build an instance of UsAppToPersonInstance - - :param payload: Payload response from the API + :returns: ApiResponse with instance, status code, and headers """ - return UsAppToPersonInstance( + 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) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation + async def _update_async( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + x_twilio_api_version: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> tuple: """ - return "" - - -class UsAppToPersonList(ListResource): + Internal async helper for update operation - 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 + 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 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. """ @@ -470,7 +963,7 @@ def __init__(self, version: Version, messaging_service_sid: str): **self._solution ) - def create( + def _create( self, brand_registration_sid: str, description: str, @@ -479,6 +972,7 @@ def create( us_app_to_person_usecase: str, has_embedded_links: bool, has_embedded_phone: bool, + x_twilio_api_version: Union[str, object] = values.unset, opt_in_message: Union[str, object] = values.unset, opt_out_message: Union[str, object] = values.unset, help_message: Union[str, object] = values.unset, @@ -488,28 +982,14 @@ def create( subscriber_opt_in: Union[bool, object] = values.unset, age_gated: Union[bool, object] = values.unset, direct_lending: Union[bool, object] = values.unset, - ) -> UsAppToPersonInstance: + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> tuple: """ - Create the UsAppToPersonInstance + Internal helper for create operation - :param brand_registration_sid: A2P Brand Registration SID - :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. - :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. - :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. - :param us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING..] - :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. - :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. - :param opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. - :param opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. - :param help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. - :param opt_in_keywords: If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. - :param opt_out_keywords: End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. - :param help_keywords: End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. - :param subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. - :param age_gated: A boolean that specifies whether campaign is age gated or not. - :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. - - :returns: The created UsAppToPersonInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -530,21 +1010,100 @@ def create( "SubscriberOptIn": serialize.boolean_to_string(subscriber_opt_in), "AgeGated": serialize.boolean_to_string(age_gated), "DirectLending": serialize.boolean_to_string(direct_lending), + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, } ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + brand_registration_sid: str, + description: str, + message_flow: str, + message_samples: List[str], + us_app_to_person_usecase: str, + has_embedded_links: bool, + has_embedded_phone: bool, + x_twilio_api_version: Union[str, object] = values.unset, + opt_in_message: Union[str, object] = values.unset, + opt_out_message: Union[str, object] = values.unset, + help_message: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + opt_out_keywords: Union[List[str], object] = values.unset, + help_keywords: Union[List[str], object] = values.unset, + subscriber_opt_in: Union[bool, object] = values.unset, + age_gated: Union[bool, object] = values.unset, + direct_lending: Union[bool, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> UsAppToPersonInstance: + """ + Create the UsAppToPersonInstance + + :param brand_registration_sid: A2P Brand Registration SID + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING..] + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param x_twilio_api_version: The version of the Messaging API to use for this request + :param opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. + :param opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param opt_in_keywords: If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. + :param opt_out_keywords: End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param help_keywords: End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. + :param age_gated: A boolean that specifies whether campaign is age gated or not. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. + + :returns: The created UsAppToPersonInstance + """ + payload, _, _ = self._create( + brand_registration_sid=brand_registration_sid, + description=description, + message_flow=message_flow, + message_samples=message_samples, + us_app_to_person_usecase=us_app_to_person_usecase, + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + x_twilio_api_version=x_twilio_api_version, + opt_in_message=opt_in_message, + opt_out_message=opt_out_message, + help_message=help_message, + opt_in_keywords=opt_in_keywords, + opt_out_keywords=opt_out_keywords, + help_keywords=help_keywords, + subscriber_opt_in=subscriber_opt_in, + age_gated=age_gated, + direct_lending=direct_lending, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) return UsAppToPersonInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], ) - async def create_async( + def create_with_http_info( self, brand_registration_sid: str, description: str, @@ -553,6 +1112,7 @@ async def create_async( us_app_to_person_usecase: str, has_embedded_links: bool, has_embedded_phone: bool, + x_twilio_api_version: Union[str, object] = values.unset, opt_in_message: Union[str, object] = values.unset, opt_out_message: Union[str, object] = values.unset, help_message: Union[str, object] = values.unset, @@ -562,9 +1122,11 @@ async def create_async( subscriber_opt_in: Union[bool, object] = values.unset, age_gated: Union[bool, object] = values.unset, direct_lending: Union[bool, object] = values.unset, - ) -> UsAppToPersonInstance: + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Asynchronously create the UsAppToPersonInstance + Create the UsAppToPersonInstance and return response metadata :param brand_registration_sid: A2P Brand Registration SID :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. @@ -573,6 +1135,7 @@ async def create_async( :param us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING..] :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param x_twilio_api_version: The version of the Messaging API to use for this request :param opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. :param opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. :param help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. @@ -582,8 +1145,66 @@ async def create_async( :param subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. :param age_gated: A boolean that specifies whether campaign is age gated or not. :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :param privacy_policy_url: The URL of the privacy policy for the campaign. + :param terms_and_conditions_url: The URL of the terms and conditions for the campaign. - :returns: The created UsAppToPersonInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + brand_registration_sid=brand_registration_sid, + description=description, + message_flow=message_flow, + message_samples=message_samples, + us_app_to_person_usecase=us_app_to_person_usecase, + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + x_twilio_api_version=x_twilio_api_version, + opt_in_message=opt_in_message, + opt_out_message=opt_out_message, + help_message=help_message, + opt_in_keywords=opt_in_keywords, + opt_out_keywords=opt_out_keywords, + help_keywords=help_keywords, + subscriber_opt_in=subscriber_opt_in, + age_gated=age_gated, + direct_lending=direct_lending, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + ) + instance = UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + brand_registration_sid: str, + description: str, + message_flow: str, + message_samples: List[str], + us_app_to_person_usecase: str, + has_embedded_links: bool, + has_embedded_phone: bool, + x_twilio_api_version: Union[str, object] = values.unset, + opt_in_message: Union[str, object] = values.unset, + opt_out_message: Union[str, object] = values.unset, + help_message: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + opt_out_keywords: Union[List[str], object] = values.unset, + help_keywords: Union[List[str], object] = values.unset, + subscriber_opt_in: Union[bool, object] = values.unset, + age_gated: Union[bool, object] = values.unset, + direct_lending: Union[bool, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -604,22 +1225,177 @@ async def create_async( "SubscriberOptIn": serialize.boolean_to_string(subscriber_opt_in), "AgeGated": serialize.boolean_to_string(age_gated), "DirectLending": serialize.boolean_to_string(direct_lending), + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, } ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers = values.of( + { + "X-Twilio-Api-Version": x_twilio_api_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( + headers["Accept"] = "application/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]: @@ -629,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 @@ -639,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]: @@ -654,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 @@ -664,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]: @@ -678,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 @@ -687,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, ) @@ -696,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]: @@ -704,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 @@ -713,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, @@ -731,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 @@ -739,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, @@ -758,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 @@ -766,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: """ @@ -787,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: """ @@ -799,7 +1814,7 @@ async def get_page_async(self, target_url: str) -> UsAppToPersonPage: :returns: Page of UsAppToPersonInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return UsAppToPersonPage(self._version, response, self._solution) + return UsAppToPersonPage(self._version, response, solution=self._solution) def get(self, sid: str) -> UsAppToPersonContext: """ diff --git a/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py b/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py index 1f0d857047..76ab18b76c 100644 --- a/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py +++ b/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,60 +71,124 @@ def __init__(self, version: Version, messaging_service_sid: str): ) ) - def fetch( + def _fetch( self, brand_registration_sid: Union[str, object] = values.unset - ) -> UsAppToPersonUsecaseInstance: + ) -> tuple: """ - Asynchronously fetch the UsAppToPersonUsecaseInstance + Internal helper for fetch operation - :param brand_registration_sid: The unique string to identify the A2P brand. - :returns: The fetched UsAppToPersonUsecaseInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Accept"] = "application/json" + params = values.of( { "BrandRegistrationSid": brand_registration_sid, } ) - payload = self._version.fetch( + return self._version.fetch_with_response_info( method="GET", uri=self._uri, headers=headers, params=params ) + def fetch( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> UsAppToPersonUsecaseInstance: + """ + Fetch the UsAppToPersonUsecaseInstance + + :param brand_registration_sid: The unique string to identify the A2P brand. + :returns: The fetched UsAppToPersonUsecaseInstance + """ + payload, _, _ = self._fetch(brand_registration_sid=brand_registration_sid) return UsAppToPersonUsecaseInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], ) - async def fetch_async( + def fetch_with_http_info( self, brand_registration_sid: Union[str, object] = values.unset - ) -> UsAppToPersonUsecaseInstance: + ) -> ApiResponse: """ - Asynchronously fetch the UsAppToPersonUsecaseInstance + Fetch the UsAppToPersonUsecaseInstance and return response metadata :param brand_registration_sid: The unique string to identify the A2P brand. - :returns: The fetched UsAppToPersonUsecaseInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + brand_registration_sid=brand_registration_sid + ) + instance = UsAppToPersonUsecaseInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Accept"] = "application/json" + params = values.of( { "BrandRegistrationSid": brand_registration_sid, } ) - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers, params=params ) + async def fetch_async( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> UsAppToPersonUsecaseInstance: + """ + Asynchronously fetch the UsAppToPersonUsecaseInstance + + :param brand_registration_sid: The unique string to identify the A2P brand. + :returns: The fetched UsAppToPersonUsecaseInstance + """ + payload, _, _ = await self._fetch_async( + brand_registration_sid=brand_registration_sid + ) return UsAppToPersonUsecaseInstance( self._version, payload, messaging_service_sid=self._solution["messaging_service_sid"], ) + async def fetch_with_http_info_async( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously fetch the UsAppToPersonUsecaseInstance and return response metadata + + :param brand_registration_sid: The unique string to identify the A2P brand. + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + brand_registration_sid=brand_registration_sid + ) + instance = UsAppToPersonUsecaseInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/messaging/v1/tollfree_verification.py b/twilio/rest/messaging/v1/tollfree_verification.py index 98887c7663..844e16054e 100644 --- a/twilio/rest/messaging/v1/tollfree_verification.py +++ b/twilio/rest/messaging/v1/tollfree_verification.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,6 +25,33 @@ class TollfreeVerificationInstance(InstanceResource): + class BusinessRegistrationAuthority(object): + EIN = "EIN" + CBN = "CBN" + CRN = "CRN" + PROVINCIAL_NUMBER = "PROVINCIAL_NUMBER" + VAT = "VAT" + ACN = "ACN" + ABN = "ABN" + BRN = "BRN" + SIREN = "SIREN" + SIRET = "SIRET" + NZBN = "NZBN" + UST_IDNR = "USt-IdNr" + CIF = "CIF" + NIF = "NIF" + CNPJ = "CNPJ" + UID = "UID" + NEQ = "NEQ" + OTHER = "OTHER" + + class BusinessType(object): + PRIVATE_PROFIT = "PRIVATE_PROFIT" + PUBLIC_PROFIT = "PUBLIC_PROFIT" + SOLE_PROPRIETOR = "SOLE_PROPRIETOR" + NON_PROFIT = "NON_PROFIT" + GOVERNMENT = "GOVERNMENT" + class OptInType(object): VERBAL = "VERBAL" WEB_FORM = "WEB_FORM" @@ -31,6 +59,7 @@ class OptInType(object): VIA_TEXT = "VIA_TEXT" MOBILE_QR_CODE = "MOBILE_QR_CODE" IMPORT = "IMPORT" + IMPORT_PLEASE_REPLACE = "IMPORT_PLEASE_REPLACE" class Status(object): PENDING_REVIEW = "PENDING_REVIEW" @@ -38,6 +67,9 @@ class Status(object): TWILIO_APPROVED = "TWILIO_APPROVED" TWILIO_REJECTED = "TWILIO_REJECTED" + class VettingProvider(object): + CAMPAIGN_VERIFY = "CAMPAIGN_VERIFY" + """ :ivar sid: The unique string to identify Tollfree Verification. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tollfree Verification resource. @@ -59,7 +91,7 @@ class Status(object): :ivar business_contact_email: The email address of the contact for the business or organization using the Tollfree number. :ivar business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. :ivar notification_email: The email address to receive the notification about the verification result. . - :ivar use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :ivar use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. :ivar use_case_summary: Use this to further explain how messaging is used by the business or organization. :ivar production_message_sample: An example of message content, i.e. a sample message. :ivar opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. @@ -67,15 +99,31 @@ class Status(object): :ivar message_volume: Estimate monthly volume of messages from the Tollfree Number. :ivar additional_information: Additional information to be provided for verification. :ivar tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :ivar tollfree_phone_number: The E.164 formatted toll-free phone number associated with the verification. :ivar status: :ivar url: The absolute URL of the Tollfree Verification resource. :ivar rejection_reason: The rejection reason given when a Tollfree Verification has been rejected. :ivar error_code: The error code given when a Tollfree Verification has been rejected. :ivar edit_expiration: The date and time when the ability to edit a rejected verification expires. :ivar edit_allowed: If a rejected verification is allowed to be edited/resubmitted. Some rejection reasons allow editing and some do not. + :ivar business_registration_number: A legally recognized business registration number + :ivar business_registration_authority: + :ivar business_registration_country: Country business is registered in + :ivar business_type: + :ivar business_registration_phone_number: The E.164 formatted number associated with the business. + :ivar doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :ivar opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :ivar help_message_sample: A sample help message provided to users. + :ivar privacy_policy_url: The URL to the privacy policy for the business or organization. + :ivar terms_and_conditions_url: The URL of the terms and conditions for the business or organization. + :ivar age_gated_content: Indicates if the content is age gated. + :ivar opt_in_keywords: List of keywords that users can send to opt in or out of messages. :ivar rejection_reasons: A list of rejection reasons and codes describing why a Tollfree Verification has been rejected. :ivar resource_links: The URLs of the documents associated with the Tollfree Verification resource. :ivar external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + :ivar vetting_id: + :ivar vetting_provider: + :ivar vetting_id_expiration: """ def __init__( @@ -121,8 +169,8 @@ def __init__( "business_contact_phone" ) self.notification_email: Optional[str] = payload.get("notification_email") - self.use_case_categories: Optional[List[str]] = payload.get( - "use_case_categories" + self.use_case_categories: Optional["TollfreeVerificationInstance.str]"] = ( + payload.get("use_case_categories") ) self.use_case_summary: Optional[str] = payload.get("use_case_summary") self.production_message_sample: Optional[str] = payload.get( @@ -139,6 +187,7 @@ def __init__( self.tollfree_phone_number_sid: Optional[str] = payload.get( "tollfree_phone_number_sid" ) + self.tollfree_phone_number: Optional[str] = payload.get("tollfree_phone_number") self.status: Optional["TollfreeVerificationInstance.Status"] = payload.get( "status" ) @@ -149,15 +198,49 @@ def __init__( payload.get("edit_expiration") ) self.edit_allowed: Optional[bool] = payload.get("edit_allowed") + self.business_registration_number: Optional[str] = payload.get( + "business_registration_number" + ) + self.business_registration_authority: Optional[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority" + ] = payload.get("business_registration_authority") + self.business_registration_country: Optional[str] = payload.get( + "business_registration_country" + ) + self.business_type: Optional["TollfreeVerificationInstance.BusinessType"] = ( + payload.get("business_type") + ) + self.business_registration_phone_number: Optional[str] = payload.get( + "business_registration_phone_number" + ) + self.doing_business_as: Optional[str] = payload.get("doing_business_as") + self.opt_in_confirmation_message: Optional[str] = payload.get( + "opt_in_confirmation_message" + ) + self.help_message_sample: Optional[str] = payload.get("help_message_sample") + self.privacy_policy_url: Optional[str] = payload.get("privacy_policy_url") + self.terms_and_conditions_url: Optional[str] = payload.get( + "terms_and_conditions_url" + ) + self.age_gated_content: Optional[bool] = payload.get("age_gated_content") + self.opt_in_keywords: Optional[List[str]] = payload.get("opt_in_keywords") self.rejection_reasons: Optional[List[Dict[str, object]]] = payload.get( "rejection_reasons" ) self.resource_links: Optional[Dict[str, object]] = payload.get("resource_links") self.external_reference_id: Optional[str] = payload.get("external_reference_id") + self.vetting_id: Optional[str] = payload.get("vetting_id") + self.vetting_provider: Optional[ + "TollfreeVerificationInstance.VettingProvider" + ] = payload.get("vetting_provider") + self.vetting_id_expiration: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("vetting_id_expiration") + ) self._solution = { "sid": sid or self.sid, } + self._context: Optional[TollfreeVerificationContext] = None @property @@ -193,6 +276,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TollfreeVerificationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TollfreeVerificationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TollfreeVerificationInstance": """ Fetch the TollfreeVerificationInstance @@ -211,6 +312,24 @@ async def fetch_async(self) -> "TollfreeVerificationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TollfreeVerificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TollfreeVerificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, business_name: Union[str, object] = values.unset, @@ -236,6 +355,26 @@ def update( business_contact_email: Union[str, object] = values.unset, business_contact_phone: Union[str, object] = values.unset, edit_reason: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, ) -> "TollfreeVerificationInstance": """ Update the TollfreeVerificationInstance @@ -243,7 +382,7 @@ def update( :param business_name: The name of the business or organization using the Tollfree number. :param business_website: The website of the business or organization using the Tollfree number. :param notification_email: The email address to receive the notification about the verification result. . - :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. :param use_case_summary: Use this to further explain how messaging is used by the business or organization. :param production_message_sample: An example of message content, i.e. a sample message. :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. @@ -261,6 +400,20 @@ def update( :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting :returns: The updated TollfreeVerificationInstance """ @@ -286,6 +439,20 @@ def update( business_contact_email=business_contact_email, business_contact_phone=business_contact_phone, edit_reason=edit_reason, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, ) async def update_async( @@ -313,6 +480,26 @@ async def update_async( business_contact_email: Union[str, object] = values.unset, business_contact_phone: Union[str, object] = values.unset, edit_reason: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, ) -> "TollfreeVerificationInstance": """ Asynchronous coroutine to update the TollfreeVerificationInstance @@ -320,7 +507,7 @@ async def update_async( :param business_name: The name of the business or organization using the Tollfree number. :param business_website: The website of the business or organization using the Tollfree number. :param notification_email: The email address to receive the notification about the verification result. . - :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. :param use_case_summary: Use this to further explain how messaging is used by the business or organization. :param production_message_sample: An example of message content, i.e. a sample message. :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. @@ -338,6 +525,20 @@ async def update_async( :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting :returns: The updated TollfreeVerificationInstance """ @@ -363,98 +564,23 @@ async def update_async( business_contact_email=business_contact_email, business_contact_phone=business_contact_phone, edit_reason=edit_reason, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, ) - def __repr__(self) -> str: - """ - 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 delete(self) -> bool: - """ - Deletes the TollfreeVerificationInstance - - - :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 TollfreeVerificationInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - 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, @@ -479,14 +605,34 @@ def update( business_contact_email: Union[str, object] = values.unset, business_contact_phone: Union[str, object] = values.unset, edit_reason: Union[str, object] = values.unset, - ) -> TollfreeVerificationInstance: + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> 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. @@ -504,46 +650,62 @@ def update( :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. - - :returns: The updated TollfreeVerificationInstance - """ - data = values.of( - { - "BusinessName": business_name, - "BusinessWebsite": business_website, - "NotificationEmail": notification_email, - "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), - "UseCaseSummary": use_case_summary, - "ProductionMessageSample": production_message_sample, - "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), - "OptInType": opt_in_type, - "MessageVolume": message_volume, - "BusinessStreetAddress": business_street_address, - "BusinessStreetAddress2": business_street_address2, - "BusinessCity": business_city, - "BusinessStateProvinceRegion": business_state_province_region, - "BusinessPostalCode": business_postal_code, - "BusinessCountry": business_country, - "AdditionalInformation": additional_information, - "BusinessContactFirstName": business_contact_first_name, - "BusinessContactLastName": business_contact_last_name, - "BusinessContactEmail": business_contact_email, - "BusinessContactPhone": business_contact_phone, - "EditReason": edit_reason, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return TollfreeVerificationInstance( - self._version, payload, sid=self._solution["sid"] + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + edit_reason=edit_reason, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, ) - async def update_async( + async def update_with_http_info_async( self, business_name: Union[str, object] = values.unset, business_website: Union[str, object] = values.unset, @@ -568,14 +730,34 @@ async def update_async( business_contact_email: Union[str, object] = values.unset, business_contact_phone: Union[str, object] = values.unset, edit_reason: Union[str, object] = values.unset, - ) -> 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: """ - 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. @@ -593,43 +775,59 @@ async def update_async( :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. - - :returns: The updated TollfreeVerificationInstance - """ - data = values.of( - { - "BusinessName": business_name, - "BusinessWebsite": business_website, - "NotificationEmail": notification_email, - "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), - "UseCaseSummary": use_case_summary, - "ProductionMessageSample": production_message_sample, - "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), - "OptInType": opt_in_type, - "MessageVolume": message_volume, - "BusinessStreetAddress": business_street_address, - "BusinessStreetAddress2": business_street_address2, - "BusinessCity": business_city, - "BusinessStateProvinceRegion": business_state_province_region, - "BusinessPostalCode": business_postal_code, - "BusinessCountry": business_country, - "AdditionalInformation": additional_information, - "BusinessContactFirstName": business_contact_first_name, - "BusinessContactLastName": business_contact_last_name, - "BusinessContactEmail": business_contact_email, - "BusinessContactPhone": business_contact_phone, - "EditReason": edit_reason, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return TollfreeVerificationInstance( - self._version, payload, sid=self._solution["sid"] + :param business_registration_number: A legally recognized business registration number + :param business_registration_authority: + :param business_registration_country: Country business is registered in + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + edit_reason=edit_reason, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, ) def __repr__(self) -> str: @@ -639,40 +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): +class TollfreeVerificationContext(InstanceContext): - def get_instance(self, payload: Dict[str, Any]) -> TollfreeVerificationInstance: + 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({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: + """ + Deletes the TollfreeVerificationInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TollfreeVerificationInstance and return response metadata + + + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete() + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return 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): + 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) """ - Initialize the TollfreeVerificationList - :param version: Version that contains the resource + 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"}) - """ - super().__init__(version) + headers["Content-Type"] = "application/x-www-form-urlencoded" - self._uri = "/Tollfree/Verifications" + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) def create( self, @@ -699,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 @@ -706,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. @@ -726,9 +1952,247 @@ def create( :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. :param external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + :param business_registration_number: A legally recognized business registration number. Required for all business types except SOLE_PROPRIETOR. + :param business_registration_authority: + :param business_registration_country: The country where the business is registered. Required for all business types except SOLE_PROPRIETOR. + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting :returns: The created TollfreeVerificationInstance """ + payload, _, _ = self._create( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + tollfree_phone_number_sid=tollfree_phone_number_sid, + customer_profile_sid=customer_profile_sid, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + external_reference_id=external_reference_id, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + return TollfreeVerificationInstance(self._version, payload) + + def create_with_http_info( + self, + business_name: str, + business_website: str, + notification_email: str, + use_case_categories: List[str], + use_case_summary: str, + production_message_sample: str, + opt_in_image_urls: List[str], + opt_in_type: "TollfreeVerificationInstance.OptInType", + message_volume: str, + tollfree_phone_number_sid: str, + customer_profile_sid: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the TollfreeVerificationInstance and return response metadata + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param customer_profile_sid: Customer's Profile Bundle BundleSid. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + :param business_registration_number: A legally recognized business registration number. Required for all business types except SOLE_PROPRIETOR. + :param business_registration_authority: + :param business_registration_country: The country where the business is registered. Required for all business types except SOLE_PROPRIETOR. + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + tollfree_phone_number_sid=tollfree_phone_number_sid, + customer_profile_sid=customer_profile_sid, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + external_reference_id=external_reference_id, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, + ) + instance = TollfreeVerificationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + business_name: str, + business_website: str, + notification_email: str, + use_case_categories: List[str], + use_case_summary: str, + production_message_sample: str, + opt_in_image_urls: List[str], + opt_in_type: "TollfreeVerificationInstance.OptInType", + message_volume: str, + tollfree_phone_number_sid: str, + customer_profile_sid: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -755,16 +2219,32 @@ 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"}) - payload = self._version.create( + 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 ) - return TollfreeVerificationInstance(self._version, payload) - async def create_async( self, business_name: str, @@ -790,6 +2270,26 @@ 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, + 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 @@ -797,7 +2297,7 @@ async def create_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. @@ -817,44 +2317,194 @@ async def create_async( :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. :param 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 """ - - 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._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, ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + return TollfreeVerificationInstance(self._version, payload) + + async def create_with_http_info_async( + self, + business_name: str, + business_website: str, + notification_email: str, + use_case_categories: List[str], + use_case_summary: str, + production_message_sample: str, + opt_in_image_urls: List[str], + opt_in_type: "TollfreeVerificationInstance.OptInType", + message_volume: str, + tollfree_phone_number_sid: str, + customer_profile_sid: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[ + "TollfreeVerificationInstance.BusinessRegistrationAuthority", object + ] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "TollfreeVerificationInstance.BusinessType", object + ] = values.unset, + business_registration_phone_number: Union[str, object] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_provider: Union[ + "TollfreeVerificationInstance.VettingProvider", object + ] = values.unset, + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TollfreeVerificationInstance and return response metadata - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many as are applicable. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param customer_profile_sid: Customer's Profile Bundle BundleSid. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + :param business_registration_number: A legally recognized business registration number. Required for all business types except SOLE_PROPRIETOR. + :param business_registration_authority: + :param business_registration_country: The country where the business is registered. Required for all business types except SOLE_PROPRIETOR. + :param business_type: + :param business_registration_phone_number: The E.164 formatted number associated with the business. + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + tollfree_phone_number_sid=tollfree_phone_number_sid, + customer_profile_sid=customer_profile_sid, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + external_reference_id=external_reference_id, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + business_registration_phone_number=business_registration_phone_number, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + opt_in_keywords=opt_in_keywords, + vetting_provider=vetting_provider, + vetting_id=vetting_id, ) - - return TollfreeVerificationInstance(self._version, payload) + instance = TollfreeVerificationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -862,6 +2512,7 @@ def stream( status: Union["TollfreeVerificationInstance.Status", object] = values.unset, external_reference_id: Union[str, object] = values.unset, include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> Iterator[TollfreeVerificationInstance]: @@ -875,6 +2526,7 @@ def stream( :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -890,6 +2542,7 @@ def stream( status=status, external_reference_id=external_reference_id, include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, page_size=limits["page_size"], ) @@ -901,6 +2554,7 @@ async def stream_async( status: Union["TollfreeVerificationInstance.Status", object] = values.unset, external_reference_id: Union[str, object] = values.unset, include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> AsyncIterator[TollfreeVerificationInstance]: @@ -914,6 +2568,7 @@ async def stream_async( :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications :param limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -929,17 +2584,101 @@ async def stream_async( status=status, external_reference_id=external_reference_id, include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, page_size=limits["page_size"], ) return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TollfreeVerificationInstance and returns headers from first page + + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TollfreeVerificationInstance and returns headers from first page + + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, tollfree_phone_number_sid: Union[str, object] = values.unset, status: Union["TollfreeVerificationInstance.Status", object] = values.unset, external_reference_id: Union[str, object] = values.unset, include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[TollfreeVerificationInstance]: @@ -952,6 +2691,7 @@ def list( :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -961,12 +2701,14 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( tollfree_phone_number_sid=tollfree_phone_number_sid, status=status, external_reference_id=external_reference_id, include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, limit=limit, page_size=page_size, ) @@ -978,6 +2720,7 @@ async def list_async( status: Union["TollfreeVerificationInstance.Status", object] = values.unset, external_reference_id: Union[str, object] = values.unset, include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[TollfreeVerificationInstance]: @@ -990,6 +2733,7 @@ async def list_async( :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications :param limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param page_size: Number of records to fetch per request, when not set will use @@ -999,6 +2743,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1006,17 +2751,99 @@ async def list_async( status=status, external_reference_id=external_reference_id, include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, limit=limit, page_size=page_size, ) ] + def list_with_http_info( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TollfreeVerificationInstance and returns headers from first page + + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TollfreeVerificationInstance and returns headers from first page + + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param List[str] trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + trust_product_sid=trust_product_sid, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, tollfree_phone_number_sid: Union[str, object] = values.unset, status: Union["TollfreeVerificationInstance.Status", object] = values.unset, external_reference_id: Union[str, object] = values.unset, include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -1029,6 +2856,7 @@ def page( :param status: The compliance status of the Tollfree Verification record. :param external_reference_id: Customer supplied reference id for the Tollfree Verification record. :param include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -1041,13 +2869,20 @@ def page( "Status": status, "ExternalReferenceId": external_reference_id, "IncludeSubAccounts": serialize.boolean_to_string(include_sub_accounts), + "TrustProductSid": serialize.map(trust_product_sid, lambda e: e), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - 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( @@ -1056,6 +2891,7 @@ async def page_async( status: Union["TollfreeVerificationInstance.Status", object] = values.unset, external_reference_id: Union[str, object] = values.unset, include_sub_accounts: Union[bool, object] = values.unset, + trust_product_sid: Union[List[str], object] = values.unset, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -1068,6 +2904,7 @@ async def page_async( :param status: The compliance status of the Tollfree Verification record. :param external_reference_id: Customer supplied reference id for the Tollfree Verification record. :param include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param trust_product_sid: The trust product sids / tollfree bundle sids of tollfree verifications :param page_token: PageToken provided by the API :param page_number: Page Number, this value is simply for client state :param page_size: Number of records to return, defaults to 50 @@ -1080,17 +2917,122 @@ async def page_async( "Status": status, "ExternalReferenceId": external_reference_id, "IncludeSubAccounts": serialize.boolean_to_string(include_sub_accounts), + "TrustProductSid": serialize.map(trust_product_sid, lambda e: e), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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 118c9c895e..46e9bf390f 100644 --- a/twilio/rest/messaging/v1/usecase.py +++ b/twilio/rest/messaging/v1/usecase.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,34 +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 """ - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + payload, _, _ = self._fetch() + return UsecaseInstance(self._version, payload) - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UsecaseInstance and return response metadata - return UsecaseInstance(self._version, payload) - async def fetch_async(self) -> UsecaseInstance: + :returns: ApiResponse with instance, status code, and headers """ - Asynchronously fetch the UsecaseInstance + 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: The fetched UsecaseInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.fetch_async( + headers["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._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 795ee96566..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,29 +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 22010d62e5..0000000000 --- a/twilio/rest/microvisor/v1/__init__.py +++ /dev/null @@ -1,67 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Microvisor - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from typing import Optional -from twilio.base.version import Version -from twilio.base.domain import Domain -from twilio.rest.microvisor.v1.account_config import AccountConfigList -from twilio.rest.microvisor.v1.account_secret import AccountSecretList -from twilio.rest.microvisor.v1.app import AppList -from twilio.rest.microvisor.v1.device import DeviceList - - -class V1(Version): - - def __init__(self, domain: Domain): - """ - Initialize the V1 version of Microvisor - - :param domain: The Twilio.microvisor domain - """ - super().__init__(domain, "v1") - self._account_configs: Optional[AccountConfigList] = None - self._account_secrets: Optional[AccountSecretList] = None - self._apps: Optional[AppList] = None - self._devices: Optional[DeviceList] = None - - @property - def account_configs(self) -> AccountConfigList: - if self._account_configs is None: - self._account_configs = AccountConfigList(self) - return self._account_configs - - @property - def account_secrets(self) -> AccountSecretList: - if self._account_secrets is None: - self._account_secrets = AccountSecretList(self) - return self._account_secrets - - @property - def apps(self) -> AppList: - if self._apps is None: - self._apps = AppList(self) - return self._apps - - @property - def devices(self) -> DeviceList: - if self._devices is None: - self._devices = DeviceList(self) - return self._devices - - def __repr__(self) -> str: - """ - Provide a friendly representation - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/microvisor/v1/account_config.py b/twilio/rest/microvisor/v1/account_config.py deleted file mode 100644 index 0abe5f9288..0000000000 --- a/twilio/rest/microvisor/v1/account_config.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 - - -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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AccountConfigInstance(self._version, payload) - - async def create_async(self, key: str, value: str) -> AccountConfigInstance: - """ - Asynchronously create the AccountConfigInstance - - :param key: The config key; up to 100 characters. - :param value: The config value; up to 4096 characters. - - :returns: The created AccountConfigInstance - """ - - data = values.of( - { - "Key": key, - "Value": value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AccountConfigInstance(self._version, payload) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[AccountConfigInstance]: - """ - Streams AccountConfigInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[AccountConfigInstance]: - """ - Asynchronously streams AccountConfigInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AccountConfigInstance]: - """ - Lists AccountConfigInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AccountConfigInstance]: - """ - Asynchronously lists AccountConfigInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AccountConfigPage: - """ - Retrieve a single page of AccountConfigInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AccountConfigInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - 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 e85a78bc58..0000000000 --- a/twilio/rest/microvisor/v1/account_secret.py +++ /dev/null @@ -1,551 +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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AccountSecretInstance(self._version, payload) - - async def create_async(self, key: str, value: str) -> AccountSecretInstance: - """ - Asynchronously create the AccountSecretInstance - - :param key: The secret key; up to 100 characters. - :param value: The secret value; up to 4096 characters. - - :returns: The created AccountSecretInstance - """ - - data = values.of( - { - "Key": key, - "Value": value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return AccountSecretInstance(self._version, payload) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[AccountSecretInstance]: - """ - Streams AccountSecretInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[AccountSecretInstance]: - """ - Asynchronously streams AccountSecretInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AccountSecretInstance]: - """ - Lists AccountSecretInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[AccountSecretInstance]: - """ - Asynchronously lists AccountSecretInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> AccountSecretPage: - """ - Retrieve a single page of AccountSecretInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of AccountSecretInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - 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 0c91fe3c50..0000000000 --- a/twilio/rest/microvisor/v1/app/__init__.py +++ /dev/null @@ -1,469 +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 4f9eab075e..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 42a17340f6..0000000000 --- a/twilio/rest/microvisor/v1/device/__init__.py +++ /dev/null @@ -1,566 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Microvisor - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page -from twilio.rest.microvisor.v1.device.device_config import DeviceConfigList -from twilio.rest.microvisor.v1.device.device_secret import DeviceSecretList - - -class DeviceInstance(InstanceResource): - """ - :ivar sid: A 34-character string that uniquely identifies this Device. - :ivar unique_name: A developer-defined string that uniquely identifies the Device. This value must be unique for all Devices on this Account. The `unique_name` value may be used as an alternative to the `sid` in the URL path to address the resource. - :ivar account_sid: The unique SID identifier of the Account. - :ivar app: Information about the target App and the App reported by this Device. Contains the properties `target_sid`, `date_targeted`, `update_status` (one of `up-to-date`, `pending` and `error`), `update_error_code`, `reported_sid` and `date_reported`. - :ivar logging: Object specifying whether application logging is enabled for this Device. Contains the properties `enabled` and `date_expires`. - :ivar date_created: The date that this Device was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar date_updated: The date that this Device was last updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :ivar url: The URL of this resource. - :ivar links: The absolute URLs of related resources. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.account_sid: Optional[str] = payload.get("account_sid") - self.app: Optional[Dict[str, object]] = payload.get("app") - self.logging: Optional[Dict[str, object]] = payload.get("logging") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.url: Optional[str] = payload.get("url") - self.links: Optional[Dict[str, object]] = payload.get("links") - - self._solution = { - "sid": sid or self.sid, - } - self._context: Optional[DeviceContext] = None - - @property - def _proxy(self) -> "DeviceContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: DeviceContext for this DeviceInstance - """ - if self._context is None: - self._context = DeviceContext( - self._version, - sid=self._solution["sid"], - ) - return self._context - - def fetch(self) -> "DeviceInstance": - """ - Fetch the DeviceInstance - - - :returns: The fetched DeviceInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "DeviceInstance": - """ - Asynchronous coroutine to fetch the DeviceInstance - - - :returns: The fetched DeviceInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - unique_name: Union[str, object] = values.unset, - target_app: Union[str, object] = values.unset, - logging_enabled: Union[bool, object] = values.unset, - restart_app: Union[bool, object] = values.unset, - ) -> "DeviceInstance": - """ - Update the DeviceInstance - - :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID. - :param target_app: The SID or unique name of the App to be targeted to the Device. - :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours. - :param restart_app: Set to true to restart the App running on the Device. - - :returns: The updated DeviceInstance - """ - return self._proxy.update( - unique_name=unique_name, - target_app=target_app, - logging_enabled=logging_enabled, - restart_app=restart_app, - ) - - async def update_async( - self, - unique_name: Union[str, object] = values.unset, - target_app: Union[str, object] = values.unset, - logging_enabled: Union[bool, object] = values.unset, - restart_app: Union[bool, object] = values.unset, - ) -> "DeviceInstance": - """ - Asynchronous coroutine to update the DeviceInstance - - :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID. - :param target_app: The SID or unique name of the App to be targeted to the Device. - :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours. - :param restart_app: Set to true to restart the App running on the Device. - - :returns: The updated DeviceInstance - """ - return await self._proxy.update_async( - unique_name=unique_name, - target_app=target_app, - logging_enabled=logging_enabled, - restart_app=restart_app, - ) - - @property - def device_configs(self) -> DeviceConfigList: - """ - Access the device_configs - """ - return self._proxy.device_configs - - @property - def device_secrets(self) -> DeviceSecretList: - """ - Access the device_secrets - """ - return self._proxy.device_secrets - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".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, - restart_app: Union[bool, object] = values.unset, - ) -> DeviceInstance: - """ - Update the DeviceInstance - - :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID. - :param target_app: The SID or unique name of the App to be targeted to the Device. - :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours. - :param restart_app: Set to true to restart the App running on the Device. - - :returns: The updated DeviceInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "TargetApp": target_app, - "LoggingEnabled": serialize.boolean_to_string(logging_enabled), - "RestartApp": serialize.boolean_to_string(restart_app), - } - ) - - 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, - restart_app: Union[bool, object] = values.unset, - ) -> DeviceInstance: - """ - Asynchronous coroutine to update the DeviceInstance - - :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID. - :param target_app: The SID or unique name of the App to be targeted to the Device. - :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours. - :param restart_app: Set to true to restart the App running on the Device. - - :returns: The updated DeviceInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "TargetApp": target_app, - "LoggingEnabled": serialize.boolean_to_string(logging_enabled), - "RestartApp": serialize.boolean_to_string(restart_app), - } - ) - - 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 b4759e90b0..0000000000 --- a/twilio/rest/microvisor/v1/device/device_config.py +++ /dev/null @@ -1,590 +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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceConfigInstance( - self._version, payload, device_sid=self._solution["device_sid"] - ) - - async def create_async(self, key: str, value: str) -> DeviceConfigInstance: - """ - Asynchronously create the DeviceConfigInstance - - :param key: The config key; up to 100 characters. - :param value: The config value; up to 4096 characters. - - :returns: The created DeviceConfigInstance - """ - - data = values.of( - { - "Key": key, - "Value": value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceConfigInstance( - self._version, payload, device_sid=self._solution["device_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[DeviceConfigInstance]: - """ - Streams DeviceConfigInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[DeviceConfigInstance]: - """ - Asynchronously streams DeviceConfigInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DeviceConfigInstance]: - """ - Lists DeviceConfigInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DeviceConfigInstance]: - """ - Asynchronously lists DeviceConfigInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> DeviceConfigPage: - """ - Retrieve a single page of DeviceConfigInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of DeviceConfigInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - 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 f89a6c0e96..0000000000 --- a/twilio/rest/microvisor/v1/device/device_secret.py +++ /dev/null @@ -1,588 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Microvisor - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, 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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceSecretInstance( - self._version, payload, device_sid=self._solution["device_sid"] - ) - - async def create_async(self, key: str, value: str) -> DeviceSecretInstance: - """ - Asynchronously create the DeviceSecretInstance - - :param key: The secret key; up to 100 characters. - :param value: The secret value; up to 4096 characters. - - :returns: The created DeviceSecretInstance - """ - - data = values.of( - { - "Key": key, - "Value": value, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DeviceSecretInstance( - self._version, payload, device_sid=self._solution["device_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[DeviceSecretInstance]: - """ - Streams DeviceSecretInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[DeviceSecretInstance]: - """ - Asynchronously streams DeviceSecretInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DeviceSecretInstance]: - """ - Lists DeviceSecretInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DeviceSecretInstance]: - """ - Asynchronously lists DeviceSecretInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> DeviceSecretPage: - """ - Retrieve a single page of DeviceSecretInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of DeviceSecretInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - 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/v1/alert.py b/twilio/rest/monitor/v1/alert.py index ef8cf39dda..f7666a0e3b 100644 --- a/twilio/rest/monitor/v1/alert.py +++ b/twilio/rest/monitor/v1/alert.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AlertContext] = None @property @@ -114,6 +116,24 @@ async def fetch_async(self) -> "AlertInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AlertInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AlertInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,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 @@ -148,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: """ @@ -167,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: """ @@ -197,6 +269,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AlertInstance: :param payload: Payload response from the API """ + return AlertInstance(self._version, payload) def __repr__(self) -> str: @@ -293,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, @@ -318,6 +461,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( log_level=log_level, @@ -353,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( @@ -364,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, @@ -397,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( @@ -433,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 6b67a9c029..e568c814e1 100644 --- a/twilio/rest/monitor/v1/event.py +++ b/twilio/rest/monitor/v1/event.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,7 +26,7 @@ class EventInstance(InstanceResource): """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Event resource. - :ivar actor_sid: The SID of the actor that caused the event, if available. Can be `null`. + :ivar actor_sid: The SID of the actor that caused the event, if available. This can be either a User ID (matching the pattern `^US[0-9a-fA-F]{32}$`) or an Account SID (matching the pattern `^AC[0-9a-fA-F]{32}$`). If the actor's SID isn't available, this field will be `null`. :ivar actor_type: The type of actor that caused the event. Can be: `user` for a change made by a logged-in user in the Twilio Console, `account` for an event caused by an API request by an authenticating Account, `twilio-admin` for an event caused by a Twilio employee, and so on. :ivar description: A description of the event. Can be `null`. :ivar event_data: An object with additional data about the event. The contents depend on `event_type`. For example, event-types of the form `RESOURCE.updated`, this value contains a `resource_properties` dictionary that describes the previous and updated properties of the resource. @@ -65,6 +66,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EventContext] = None @property @@ -100,6 +102,24 @@ async def fetch_async(self) -> "EventInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -127,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 @@ -134,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: """ @@ -153,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: """ @@ -183,6 +255,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EventInstance: :param payload: Payload response from the API """ + return EventInstance(self._version, payload) def __repr__(self) -> str: @@ -297,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, @@ -328,6 +489,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( actor_sid=actor_sid, @@ -372,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( @@ -386,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, @@ -428,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( @@ -473,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/v1/credential.py b/twilio/rest/notify/v1/credential.py index d894a9a702..9bbd8bd0fc 100644 --- a/twilio/rest/notify/v1/credential.py +++ b/twilio/rest/notify/v1/credential.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -96,6 +98,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialInstance": """ Fetch the CredentialInstance @@ -114,6 +134,24 @@ async def fetch_async(self) -> "CredentialInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -174,6 +212,66 @@ async def update_async( secret=secret, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CredentialInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -201,6 +299,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Credentials/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialInstance @@ -208,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: @@ -220,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: @@ -232,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: """ @@ -251,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, @@ -284,6 +514,64 @@ 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, @@ -294,14 +582,15 @@ def update( "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, @@ -324,24 +613,47 @@ async def update_async( :returns: The updated CredentialInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": serialize.boolean_to_string(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: """ @@ -361,6 +673,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: :param payload: Payload response from the API """ + return CredentialInstance(self._version, payload) def __repr__(self) -> str: @@ -385,7 +698,7 @@ def __init__(self, version: Version): self._uri = "/Credentials" - def create( + def _create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -394,19 +707,12 @@ def create( sandbox: Union[bool, object] = values.unset, api_key: Union[str, object] = values.unset, secret: Union[str, object] = values.unset, - ) -> CredentialInstance: + ) -> tuple: """ - Create the CredentialInstance + Internal helper for create operation - :param type: - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` - :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` - :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. - :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. - :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. - - :returns: The created CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -422,13 +728,15 @@ def create( ) headers = values.of({"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 CredentialInstance(self._version, payload) - - async def create_async( + def create( self, type: "CredentialInstance.PushService", friendly_name: Union[str, object] = values.unset, @@ -439,7 +747,7 @@ async def create_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronously create the CredentialInstance + Create the CredentialInstance :param type: :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. @@ -451,6 +759,68 @@ async def create_async( :returns: The created CredentialInstance """ + payload, _, _ = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + return CredentialInstance(self._version, payload) + + def create_with_http_info( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -465,12 +835,83 @@ async def create_async( ) headers = values.of({"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, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + payload, _, _ = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) return CredentialInstance(self._version, payload) + async def create_with_http_info_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CredentialInstance and return response metadata + + :param type: + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + instance = CredentialInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -521,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, @@ -540,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -566,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( @@ -574,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, @@ -598,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( @@ -625,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 2654c97c14..629a7f2ae2 100644 --- a/twilio/rest/notify/v1/service/__init__.py +++ b/twilio/rest/notify/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -93,6 +94,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -128,6 +130,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -146,6 +166,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -254,6 +292,114 @@ async def update_async( delivery_callback_enabled=delivery_callback_enabled, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + @property def bindings(self) -> BindingList: """ @@ -298,6 +444,20 @@ def __init__(self, version: Version, sid: str): self._bindings: Optional[BindingList] = None self._notifications: Optional[NotificationList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ServiceInstance @@ -305,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: @@ -317,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: @@ -329,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: """ @@ -348,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, @@ -376,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/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. - :param facebook_messenger_page_id: Deprecated. - :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. - :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. - :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. - :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. - :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. - :param alexa_skill_id: Deprecated. - :param default_alexa_notification_protocol_version: Deprecated. - :param delivery_callback_url: URL to send delivery status callback. - :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + Internal helper for update operation - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -417,16 +646,17 @@ def update( ), } ) + 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, @@ -444,7 +674,7 @@ async def update_async( delivery_callback_enabled: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Asynchronous coroutine to update the ServiceInstance + Update the ServiceInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. @@ -463,49 +693,259 @@ async def update_async( :returns: The updated ServiceInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "ApnCredentialSid": apn_credential_sid, - "GcmCredentialSid": gcm_credential_sid, - "MessagingServiceSid": messaging_service_sid, - "FacebookMessengerPageId": facebook_messenger_page_id, - "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, - "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, - "FcmCredentialSid": fcm_credential_sid, - "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, - "LogEnabled": serialize.boolean_to_string(log_enabled), - "AlexaSkillId": alexa_skill_id, - "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, - "DeliveryCallbackUrl": delivery_callback_url, - "DeliveryCallbackEnabled": serialize.boolean_to_string( - delivery_callback_enabled - ), - } - ) - - 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 - """ - if self._bindings is None: - self._bindings = BindingList( - self._version, - self._solution["sid"], - ) - return self._bindings - - @property - def notifications(self) -> NotificationList: + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The updated ServiceInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings + + @property + def notifications(self) -> NotificationList: """ Access the notifications """ @@ -534,6 +974,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -558,7 +999,172 @@ def __init__(self, version: Version): self._uri = "/Services" - def create( + def _create( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( self, friendly_name: Union[str, object] = values.unset, apn_credential_sid: Union[str, object] = values.unset, @@ -574,26 +1180,12 @@ def create( default_alexa_notification_protocol_version: Union[str, object] = values.unset, delivery_callback_url: Union[str, object] = values.unset, delivery_callback_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Create the ServiceInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. - :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. - :param facebook_messenger_page_id: Deprecated. - :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. - :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. - :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. - :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. - :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. - :param alexa_skill_id: Deprecated. - :param default_alexa_notification_protocol_version: Deprecated. - :param delivery_callback_url: URL to send delivery status callback. - :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + Internal async helper for create operation - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -618,12 +1210,14 @@ def create( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( + 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 ) - return ServiceInstance(self._version, payload) - async def create_async( self, friendly_name: Union[str, object] = values.unset, @@ -661,34 +1255,79 @@ async def create_async( :returns: The created ServiceInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "ApnCredentialSid": apn_credential_sid, - "GcmCredentialSid": gcm_credential_sid, - "MessagingServiceSid": messaging_service_sid, - "FacebookMessengerPageId": facebook_messenger_page_id, - "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, - "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, - "FcmCredentialSid": fcm_credential_sid, - "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, - "LogEnabled": serialize.boolean_to_string(log_enabled), - "AlexaSkillId": alexa_skill_id, - "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, - "DeliveryCallbackUrl": delivery_callback_url, - "DeliveryCallbackEnabled": serialize.boolean_to_string( - delivery_callback_enabled - ), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + return ServiceInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + async def create_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata - 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 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._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, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -746,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, @@ -767,6 +1462,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -796,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( @@ -805,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, @@ -832,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( @@ -862,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 845f720dc2..e380730645 100644 --- a/twilio/rest/notify/v1/service/binding.py +++ b/twilio/rest/notify/v1/service/binding.py @@ -15,6 +15,7 @@ from datetime import date, datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -83,6 +84,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[BindingContext] = None @property @@ -119,6 +121,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "BindingInstance": """ Fetch the BindingInstance @@ -137,6 +157,24 @@ async def fetch_async(self) -> "BindingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BindingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -166,6 +204,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the BindingInstance @@ -173,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: @@ -185,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: @@ -197,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: """ @@ -217,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: """ @@ -248,6 +384,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: :param payload: Payload response from the API """ + return BindingInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -279,7 +416,7 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Bindings".format(**self._solution) - def create( + def _create( self, identity: str, binding_type: "BindingInstance.BindingType", @@ -288,19 +425,12 @@ def create( notification_protocol_version: Union[str, object] = values.unset, credential_sid: Union[str, object] = values.unset, endpoint: Union[str, object] = values.unset, - ) -> BindingInstance: + ) -> tuple: """ - Create the BindingInstance + 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/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. - :param binding_type: - :param address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. - :param tag: A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. - :param notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. - :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. - :param endpoint: Deprecated. - - :returns: The created BindingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -316,15 +446,51 @@ def create( ) headers = values.of({"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, + binding_type: "BindingInstance.BindingType", + address: str, + tag: Union[List[str], object] = values.unset, + notification_protocol_version: Union[str, object] = values.unset, + credential_sid: Union[str, object] = values.unset, + endpoint: Union[str, object] = values.unset, + ) -> BindingInstance: + """ + Create the BindingInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + :param binding_type: + :param address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + :param tag: A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. + :param notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. + :param endpoint: Deprecated. + + :returns: The created BindingInstance + """ + payload, _, _ = self._create( + identity=identity, + binding_type=binding_type, + address=address, + tag=tag, + notification_protocol_version=notification_protocol_version, + credential_sid=credential_sid, + endpoint=endpoint, + ) return BindingInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, identity: str, binding_type: "BindingInstance.BindingType", @@ -333,9 +499,9 @@ async def create_async( notification_protocol_version: Union[str, object] = values.unset, credential_sid: Union[str, object] = values.unset, endpoint: Union[str, object] = values.unset, - ) -> BindingInstance: + ) -> ApiResponse: """ - Asynchronously create the BindingInstance + Create the BindingInstance and return response metadata :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. :param binding_type: @@ -345,7 +511,37 @@ async def create_async( :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. :param endpoint: Deprecated. - :returns: The created BindingInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + binding_type=binding_type, + address=address, + tag=tag, + notification_protocol_version=notification_protocol_version, + credential_sid=credential_sid, + endpoint=endpoint, + ) + instance = BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + binding_type: "BindingInstance.BindingType", + address: str, + tag: Union[List[str], object] = values.unset, + notification_protocol_version: Union[str, object] = values.unset, + credential_sid: Union[str, object] = values.unset, + endpoint: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -361,14 +557,87 @@ async def create_async( ) headers = values.of({"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, + binding_type: "BindingInstance.BindingType", + address: str, + tag: Union[List[str], object] = values.unset, + notification_protocol_version: Union[str, object] = values.unset, + credential_sid: Union[str, object] = values.unset, + endpoint: Union[str, object] = values.unset, + ) -> BindingInstance: + """ + Asynchronously create the BindingInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + :param binding_type: + :param address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + :param tag: A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. + :param notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. + :param endpoint: Deprecated. + + :returns: The created BindingInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + binding_type=binding_type, + address=address, + tag=tag, + notification_protocol_version=notification_protocol_version, + credential_sid=credential_sid, + endpoint=endpoint, + ) return BindingInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + identity: str, + binding_type: "BindingInstance.BindingType", + address: str, + tag: Union[List[str], object] = values.unset, + notification_protocol_version: Union[str, object] = values.unset, + credential_sid: Union[str, object] = values.unset, + endpoint: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the BindingInstance and return response metadata + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + :param binding_type: + :param address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + :param tag: A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. + :param notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. + :param endpoint: Deprecated. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + binding_type=binding_type, + address=address, + tag=tag, + notification_protocol_version=notification_protocol_version, + credential_sid=credential_sid, + endpoint=endpoint, + ) + instance = BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, start_date: Union[date, object] = values.unset, @@ -447,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, @@ -474,6 +819,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( start_date=start_date, @@ -512,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( @@ -524,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, @@ -560,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, @@ -599,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: """ @@ -614,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: """ @@ -626,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 ec31b423a1..a16ef7acf1 100644 --- a/twilio/rest/notify/v1/service/notification.py +++ b/twilio/rest/notify/v1/service/notification.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -112,7 +113,7 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Notifications".format(**self._solution) - def create( + def _create( self, body: Union[str, object] = values.unset, priority: Union["NotificationInstance.Priority", object] = values.unset, @@ -132,30 +133,12 @@ def create( delivery_callback_url: Union[str, object] = values.unset, identity: Union[List[str], object] = values.unset, tag: Union[List[str], object] = values.unset, - ) -> NotificationInstance: + ) -> tuple: """ - Create the NotificationInstance + Internal helper for create operation - :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. - :param priority: - :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. - :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. - :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. - :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. - :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. - :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. - :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). - :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. - :param facebook_messenger: Deprecated. - :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. - :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. - :param alexa: Deprecated. - :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. - :param delivery_callback_url: URL to send webhooks. - :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. - :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. - - :returns: The created NotificationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -182,15 +165,84 @@ def create( ) headers = values.of({"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, + body: Union[str, object] = values.unset, + priority: Union["NotificationInstance.Priority", object] = values.unset, + ttl: Union[int, object] = values.unset, + title: Union[str, object] = values.unset, + sound: Union[str, object] = values.unset, + action: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + apn: Union[object, object] = values.unset, + gcm: Union[object, object] = values.unset, + sms: Union[object, object] = values.unset, + facebook_messenger: Union[object, object] = values.unset, + fcm: Union[object, object] = values.unset, + segment: Union[List[str], object] = values.unset, + alexa: Union[object, object] = values.unset, + to_binding: Union[List[str], object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + ) -> NotificationInstance: + """ + Create the NotificationInstance + + :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :param priority: + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). + :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :param facebook_messenger: Deprecated. + :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. + :param alexa: Deprecated. + :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. + :param delivery_callback_url: URL to send webhooks. + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. + :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. + + :returns: The created NotificationInstance + """ + payload, _, _ = self._create( + body=body, + priority=priority, + ttl=ttl, + title=title, + sound=sound, + action=action, + data=data, + apn=apn, + gcm=gcm, + sms=sms, + facebook_messenger=facebook_messenger, + fcm=fcm, + segment=segment, + alexa=alexa, + to_binding=to_binding, + delivery_callback_url=delivery_callback_url, + identity=identity, + tag=tag, + ) return NotificationInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, body: Union[str, object] = values.unset, priority: Union["NotificationInstance.Priority", object] = values.unset, @@ -210,9 +262,9 @@ async def create_async( delivery_callback_url: Union[str, object] = values.unset, identity: Union[List[str], object] = values.unset, tag: Union[List[str], object] = values.unset, - ) -> NotificationInstance: + ) -> ApiResponse: """ - Asynchronously create the NotificationInstance + Create the NotificationInstance and return response metadata :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. :param priority: @@ -233,7 +285,59 @@ async def create_async( :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. - :returns: The created NotificationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + body=body, + priority=priority, + ttl=ttl, + title=title, + sound=sound, + action=action, + data=data, + apn=apn, + gcm=gcm, + sms=sms, + facebook_messenger=facebook_messenger, + fcm=fcm, + segment=segment, + alexa=alexa, + to_binding=to_binding, + delivery_callback_url=delivery_callback_url, + identity=identity, + tag=tag, + ) + instance = NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + body: Union[str, object] = values.unset, + priority: Union["NotificationInstance.Priority", object] = values.unset, + ttl: Union[int, object] = values.unset, + title: Union[str, object] = values.unset, + sound: Union[str, object] = values.unset, + action: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + apn: Union[object, object] = values.unset, + gcm: Union[object, object] = values.unset, + sms: Union[object, object] = values.unset, + facebook_messenger: Union[object, object] = values.unset, + fcm: Union[object, object] = values.unset, + segment: Union[List[str], object] = values.unset, + alexa: Union[object, object] = values.unset, + to_binding: Union[List[str], object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -260,14 +364,153 @@ async def create_async( ) headers = values.of({"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, + body: Union[str, object] = values.unset, + priority: Union["NotificationInstance.Priority", object] = values.unset, + ttl: Union[int, object] = values.unset, + title: Union[str, object] = values.unset, + sound: Union[str, object] = values.unset, + action: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + apn: Union[object, object] = values.unset, + gcm: Union[object, object] = values.unset, + sms: Union[object, object] = values.unset, + facebook_messenger: Union[object, object] = values.unset, + fcm: Union[object, object] = values.unset, + segment: Union[List[str], object] = values.unset, + alexa: Union[object, object] = values.unset, + to_binding: Union[List[str], object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + ) -> NotificationInstance: + """ + Asynchronously create the NotificationInstance + + :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :param priority: + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). + :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :param facebook_messenger: Deprecated. + :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. + :param alexa: Deprecated. + :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. + :param delivery_callback_url: URL to send webhooks. + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. + :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. + + :returns: The created NotificationInstance + """ + payload, _, _ = await self._create_async( + body=body, + priority=priority, + ttl=ttl, + title=title, + sound=sound, + action=action, + data=data, + apn=apn, + gcm=gcm, + sms=sms, + facebook_messenger=facebook_messenger, + fcm=fcm, + segment=segment, + alexa=alexa, + to_binding=to_binding, + delivery_callback_url=delivery_callback_url, + identity=identity, + tag=tag, + ) return NotificationInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + body: Union[str, object] = values.unset, + priority: Union["NotificationInstance.Priority", object] = values.unset, + ttl: Union[int, object] = values.unset, + title: Union[str, object] = values.unset, + sound: Union[str, object] = values.unset, + action: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + apn: Union[object, object] = values.unset, + gcm: Union[object, object] = values.unset, + sms: Union[object, object] = values.unset, + facebook_messenger: Union[object, object] = values.unset, + fcm: Union[object, object] = values.unset, + segment: Union[List[str], object] = values.unset, + alexa: Union[object, object] = values.unset, + to_binding: Union[List[str], object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the NotificationInstance and return response metadata + + :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :param priority: + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). + :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :param facebook_messenger: Deprecated. + :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. + :param alexa: Deprecated. + :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. + :param delivery_callback_url: URL to send webhooks. + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. + :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + body=body, + priority=priority, + ttl=ttl, + title=title, + sound=sound, + action=action, + data=data, + apn=apn, + gcm=gcm, + sms=sms, + facebook_messenger=facebook_messenger, + fcm=fcm, + segment=segment, + alexa=alexa, + to_binding=to_binding, + delivery_callback_url=delivery_callback_url, + identity=identity, + tag=tag, + ) + instance = NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/numbers/NumbersBase.py b/twilio/rest/numbers/NumbersBase.py index 7b9e08638f..d7b4b3ee8e 100644 --- a/twilio/rest/numbers/NumbersBase.py +++ b/twilio/rest/numbers/NumbersBase.py @@ -15,6 +15,7 @@ from twilio.rest import Client from twilio.rest.numbers.v1 import V1 from twilio.rest.numbers.v2 import V2 +from twilio.rest.numbers.v3 import V3 class NumbersBase(Domain): @@ -28,6 +29,7 @@ def __init__(self, twilio: Client): super().__init__(twilio, "https://numbers.twilio.com") self._v1: Optional[V1] = None self._v2: Optional[V2] = None + self._v3: Optional[V3] = None @property def v1(self) -> V1: @@ -47,6 +49,15 @@ def v2(self) -> V2: self._v2 = V2(self) return self._v2 + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Numbers + """ + if self._v3 is None: + self._v3 = V3(self) + return self._v3 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/numbers/v1/__init__.py b/twilio/rest/numbers/v1/__init__.py index 68f078a88d..a3f3cc0847 100644 --- a/twilio/rest/numbers/v1/__init__.py +++ b/twilio/rest/numbers/v1/__init__.py @@ -17,6 +17,8 @@ from twilio.base.domain import Domain from twilio.rest.numbers.v1.bulk_eligibility import BulkEligibilityList from twilio.rest.numbers.v1.eligibility import EligibilityList +from twilio.rest.numbers.v1.embedded_session import EmbeddedSessionList +from twilio.rest.numbers.v1.porting_all_port_in import PortingAllPortInList from twilio.rest.numbers.v1.porting_port_in import PortingPortInList from twilio.rest.numbers.v1.porting_port_in_phone_number import ( PortingPortInPhoneNumberList, @@ -28,6 +30,7 @@ from twilio.rest.numbers.v1.porting_webhook_configuration_delete import ( PortingWebhookConfigurationDeleteList, ) +from twilio.rest.numbers.v1.sender_id_registration import SenderIdRegistrationList from twilio.rest.numbers.v1.signing_request_configuration import ( SigningRequestConfigurationList, ) @@ -45,6 +48,7 @@ def __init__(self, domain: Domain): super().__init__(domain, "v1") self._bulk_eligibilities: Optional[BulkEligibilityList] = None self._eligibilities: Optional[EligibilityList] = None + self._porting_all_port_ins: Optional[PortingAllPortInList] = None self._porting_port_ins: Optional[PortingPortInList] = None self._porting_port_in_phone_number: Optional[PortingPortInPhoneNumberList] = ( None @@ -56,6 +60,7 @@ def __init__(self, domain: Domain): self._porting_webhook_configurations_delete: Optional[ PortingWebhookConfigurationDeleteList ] = None + self._sender_id_registrations: Optional[SenderIdRegistrationList] = None self._signing_request_configurations: Optional[ SigningRequestConfigurationList ] = None @@ -73,6 +78,26 @@ def eligibilities(self) -> EligibilityList: self._eligibilities = EligibilityList(self) return self._eligibilities + def embedded_sessions(self, bundle_sid: str, embedded_session_id: str = None): + """ + Access the EmbeddedSessionList resource + + :param bundle_sid: The unique identifier of the registration (BU-prefixed). + + :param embedded_session_id: Optional instance ID to directly access EmbeddedSessionContext + :returns: EmbeddedSessionList instance if embedded_session_id is None, otherwise EmbeddedSessionContext + """ + list_instance = EmbeddedSessionList(self, bundle_sid) + if embedded_session_id is not None: + return list_instance(embedded_session_id) + return list_instance + + @property + def porting_all_port_ins(self) -> PortingAllPortInList: + if self._porting_all_port_ins is None: + self._porting_all_port_ins = PortingAllPortInList(self) + return self._porting_all_port_ins + @property def porting_port_ins(self) -> PortingPortInList: if self._porting_port_ins is None: @@ -107,6 +132,12 @@ def porting_webhook_configurations_delete( ) return self._porting_webhook_configurations_delete + @property + def sender_id_registrations(self) -> SenderIdRegistrationList: + if self._sender_id_registrations is None: + self._sender_id_registrations = SenderIdRegistrationList(self) + return self._sender_id_registrations + @property def signing_request_configurations(self) -> SigningRequestConfigurationList: if self._signing_request_configurations is None: diff --git a/twilio/rest/numbers/v1/bulk_eligibility.py b/twilio/rest/numbers/v1/bulk_eligibility.py index 97b358b71e..ed521218a5 100644 --- a/twilio/rest/numbers/v1/bulk_eligibility.py +++ b/twilio/rest/numbers/v1/bulk_eligibility.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -55,6 +56,7 @@ def __init__( self._solution = { "request_id": request_id or self.request_id, } + self._context: Optional[BulkEligibilityContext] = None @property @@ -90,6 +92,24 @@ async def fetch_async(self) -> "BulkEligibilityInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BulkEligibilityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BulkEligibilityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -119,6 +139,22 @@ def __init__(self, version: Version, request_id: 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) -> BulkEligibilityInstance: """ Fetch the BulkEligibilityInstance @@ -126,17 +162,43 @@ def fetch(self) -> BulkEligibilityInstance: :returns: The fetched BulkEligibilityInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return BulkEligibilityInstance( + self._version, + payload, + request_id=self._solution["request_id"], ) - return BulkEligibilityInstance( + 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: """ @@ -145,17 +207,27 @@ async def fetch_async(self) -> BulkEligibilityInstance: :returns: The fetched BulkEligibilityInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return BulkEligibilityInstance( + self._version, + payload, + request_id=self._solution["request_id"], ) - return BulkEligibilityInstance( + 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: """ @@ -180,6 +252,25 @@ def __init__(self, version: 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: @@ -190,17 +281,42 @@ def create( :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" - payload = self._version.create( + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return BulkEligibilityInstance(self._version, payload) - async def create_async( self, body: Union[object, object] = values.unset ) -> BulkEligibilityInstance: @@ -211,16 +327,22 @@ async def create_async( :returns: The created BulkEligibilityInstance """ - data = body.to_dict() + payload, _, _ = await self._create_async(body=body) + return BulkEligibilityInstance(self._version, payload) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - headers["Content-Type"] = "application/json" + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the BulkEligibilityInstance and return response metadata - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + :param body: - return BulkEligibilityInstance(self._version, payload) + :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: """ diff --git a/twilio/rest/numbers/v1/eligibility.py b/twilio/rest/numbers/v1/eligibility.py index 007a019f5b..37d6f1c07d 100644 --- a/twilio/rest/numbers/v1/eligibility.py +++ b/twilio/rest/numbers/v1/eligibility.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,25 @@ def __init__(self, version: 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 @@ -61,17 +81,42 @@ def create(self, body: Union[object, object] = values.unset) -> EligibilityInsta :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" - payload = self._version.create( + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return EligibilityInstance(self._version, payload) - async def create_async( self, body: Union[object, object] = values.unset ) -> EligibilityInstance: @@ -82,16 +127,22 @@ async def create_async( :returns: The created EligibilityInstance """ - data = body.to_dict() + payload, _, _ = await self._create_async(body=body) + return EligibilityInstance(self._version, payload) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - headers["Content-Type"] = "application/json" + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the EligibilityInstance and return response metadata - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + :param body: - return EligibilityInstance(self._version, payload) + :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: """ 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 index 50b3e328ec..53400a5fd0 100644 --- a/twilio/rest/numbers/v1/porting_port_in.py +++ b/twilio/rest/numbers/v1/porting_port_in.py @@ -12,9 +12,10 @@ Do not edit the class manually. """ -from datetime import date -from typing import Any, Dict, List, Optional, Union +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 @@ -22,19 +23,199 @@ class PortingPortInInstance(InstanceResource): + + class NumbersV1PortingAddress(object): + """ + :ivar street: The street address, ex: 101 Spear St + :ivar street_2: The building information, ex : 5th floor. + :ivar city: The city name, ex: San Francisco. + :ivar state: The state name, ex: CA or California. Note this should match the losing carrier’s information exactly. So if they spell out the entire state’s name instead of abbreviating it, please do so. + :ivar zip: The zip code, ex: 94105. + :ivar country: The country, ex: USA. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.street: Optional[str] = payload.get("street") + self.street_2: Optional[str] = payload.get("street_2") + self.city: Optional[str] = payload.get("city") + self.state: Optional[str] = payload.get("state") + self.zip: Optional[str] = payload.get("zip") + self.country: Optional[str] = payload.get("country") + + def to_dict(self): + return { + "street": self.street, + "street_2": self.street_2, + "city": self.city, + "state": self.state, + "zip": self.zip, + "country": self.country, + } + + class NumbersV1PortingLosingCarrierInformation(object): + """ + :ivar customer_name: Customer name as it is registered with the losing carrier. This can be an individual or a business name depending on the customer type selected. + :ivar account_number: The account number of the customer for the losing carrier. Only require for mobile phone numbers. + :ivar account_telephone_number: The account phone number of the customer for the losing carrier. + :ivar address_sid: If you already have an Address SID that represents the address needed for the LOA, you can provide an Address SID instead of providing the address object in the request body. This will copy the address into the port in request. If changes are made to the Address SID after port in request creation, those changes will not be reflected in the port in request. + :ivar address: + :ivar authorized_representative: The first and last name of the person listed with the losing carrier who is authorized to make changes on the account. + :ivar authorized_representative_email: Email address of the person (owner of the number) who will sign the letter of authorization for the port in request. This email address should belong to the person named in as the authorized representative. + :ivar customer_type: The type of customer account in the losing carrier. This should either be: 'Individual' or 'Business'. + :ivar authorized_representative_katakana: + :ivar sub_municipality: + :ivar building: + :ivar katakana_name: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_name: Optional[str] = payload.get("customer_name") + self.account_number: Optional[str] = payload.get("account_number") + self.account_telephone_number: Optional[str] = payload.get( + "account_telephone_number" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.address: Optional[PortingPortInList.NumbersV1PortingAddress] = ( + payload.get("address") + ) + self.authorized_representative: Optional[str] = payload.get( + "authorized_representative" + ) + self.authorized_representative_email: Optional[str] = payload.get( + "authorized_representative_email" + ) + self.customer_type: Optional["PortingPortInInstance.str"] = payload.get( + "customer_type" + ) + self.authorized_representative_katakana: Optional[str] = payload.get( + "authorized_representative_katakana" + ) + self.sub_municipality: Optional[str] = payload.get("sub_municipality") + self.building: Optional[str] = payload.get("building") + self.katakana_name: Optional[str] = payload.get("katakana_name") + + def to_dict(self): + return { + "customer_name": self.customer_name, + "account_number": self.account_number, + "account_telephone_number": self.account_telephone_number, + "address_sid": self.address_sid, + "address": self.address.to_dict() if self.address is not None else None, + "authorized_representative": self.authorized_representative, + "authorized_representative_email": self.authorized_representative_email, + "customer_type": self.customer_type, + "authorized_representative_katakana": self.authorized_representative_katakana, + "sub_municipality": self.sub_municipality, + "building": self.building, + "katakana_name": self.katakana_name, + } + + class NumbersV1PortingPortInCreate(object): + """ + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported + :ivar documents: List of document SIDs for all phone numbers included in the port in request. At least one document SID referring to a document of the type Utility Bill is required. + :ivar phone_numbers: List of phone numbers to be ported. Maximum of 1,000 phone numbers per request. + :ivar losing_carrier_information: + :ivar notification_emails: Additional emails to send a copy of the signed LOA to. + :ivar target_port_in_date: Target date to port the number. We cannot guarantee that this date will be honored by the other carriers, please work with Ops to get a confirmation of the firm order commitment (FOC) date. Expected format is ISO Local Date, example: ‘2011-12-03`. This date must be at least 7 days in the future for US ports and 10 days in the future for Japanese ports. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_start: The earliest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_end: The latest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar bundle_sid: The bundle sid is an optional identifier to reference a group of regulatory documents for a port request. + :ivar portability_advance_carrier: A field only required for Japan port in requests. It is a unique identifier for the donor carrier service the line is being ported from. + :ivar auto_cancel_approval_numbers: Japan specific field, indicates the number of phone numbers to automatically approve for cancellation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.account_sid: Optional[str] = payload.get("account_sid") + self.documents: Optional[List[str]] = payload.get("documents") + self.phone_numbers: Optional[ + List[PortingPortInList.NumbersV1PortingPortInCreatePhoneNumbers] + ] = payload.get("phone_numbers") + self.losing_carrier_information: Optional[ + PortingPortInList.NumbersV1PortingLosingCarrierInformation + ] = payload.get("losing_carrier_information") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.target_port_in_date: Optional[date] = payload.get( + "target_port_in_date" + ) + self.target_port_in_time_range_start: Optional[str] = payload.get( + "target_port_in_time_range_start" + ) + self.target_port_in_time_range_end: Optional[str] = payload.get( + "target_port_in_time_range_end" + ) + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.portability_advance_carrier: Optional[str] = payload.get( + "portability_advance_carrier" + ) + self.auto_cancel_approval_numbers: Optional[str] = payload.get( + "auto_cancel_approval_numbers" + ) + + def to_dict(self): + return { + "account_sid": self.account_sid, + "documents": self.documents, + "phone_numbers": ( + [phone_numbers.to_dict() for phone_numbers in self.phone_numbers] + if self.phone_numbers is not None + else None + ), + "losing_carrier_information": ( + self.losing_carrier_information.to_dict() + if self.losing_carrier_information is not None + else None + ), + "notification_emails": self.notification_emails, + "target_port_in_date": self.target_port_in_date, + "target_port_in_time_range_start": self.target_port_in_time_range_start, + "target_port_in_time_range_end": self.target_port_in_time_range_end, + "bundle_sid": self.bundle_sid, + "portability_advance_carrier": self.portability_advance_carrier, + "auto_cancel_approval_numbers": self.auto_cancel_approval_numbers, + } + + class NumbersV1PortingPortInCreatePhoneNumbers(object): + """ + :ivar phone_number: Phone number to be ported. This must be in the E164 Format. + :ivar pin: Some losing carriers require a PIN to authorize the port of a phone number. If the phone number is a US mobile phone number, the PIN is mandatory to process a porting request. Other carriers and number types may also require a PIN, you'll need to contact the losing carrier to determine what your phone number's PIN is. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.pin: Optional[str] = payload.get("pin") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "pin": self.pin, + } + """ :ivar port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. :ivar url: The URL of this Port In request - :ivar account_sid: The Account SID that the numbers will be added to after they are ported into Twilio. - :ivar notification_emails: List of emails for getting notifications about the LOA signing process. Allowed Max 10 emails. - :ivar target_port_in_date: Minimum number of days in the future (at least 2 days) needs to be established with the Ops team for validation. - :ivar target_port_in_time_range_start: Minimum hour in the future needs to be established with the Ops team for validation. - :ivar target_port_in_time_range_end: Maximum hour in the future needs to be established with the Ops team for validation. + :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 losing_carrier_information: The information for the losing carrier. - :ivar phone_numbers: The list of phone numbers to Port in. Phone numbers are in E.164 format (e.g. +16175551212). - :ivar documents: The list of documents SID referencing a utility bills - :ivar date_created: + :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__( @@ -63,20 +244,33 @@ def __init__( self.port_in_request_status: Optional[str] = payload.get( "port_in_request_status" ) - self.losing_carrier_information: Optional[Dict[str, object]] = payload.get( + self.order_cancellation_reason: Optional[str] = payload.get( + "order_cancellation_reason" + ) + self.losing_carrier_information: Optional[str] = payload.get( "losing_carrier_information" ) - self.phone_numbers: Optional[List[Dict[str, object]]] = payload.get( - "phone_numbers" + self.phone_numbers: Optional[List[str]] = payload.get("phone_numbers") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.portability_advance_carrier: Optional[str] = payload.get( + "portability_advance_carrier" + ) + self.auto_cancel_approval_numbers: Optional[str] = payload.get( + "auto_cancel_approval_numbers" ) self.documents: Optional[List[str]] = payload.get("documents") - self.date_created: Optional[date] = deserialize.iso8601_date( + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) + self.support_ticket_id: Optional[int] = deserialize.integer( + payload.get("support_ticket_id") + ) + self.signature_request_url: Optional[str] = payload.get("signature_request_url") self._solution = { "port_in_request_sid": port_in_request_sid or self.port_in_request_sid, } + self._context: Optional[PortingPortInContext] = None @property @@ -112,6 +306,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PortingPortInInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PortingPortInInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "PortingPortInInstance": """ Fetch the PortingPortInInstance @@ -130,6 +342,24 @@ async def fetch_async(self) -> "PortingPortInInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PortingPortInInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortInInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -142,6 +372,179 @@ def __repr__(self) -> str: class PortingPortInContext(InstanceContext): + class NumbersV1PortingAddress(object): + """ + :ivar street: The street address, ex: 101 Spear St + :ivar street_2: The building information, ex : 5th floor. + :ivar city: The city name, ex: San Francisco. + :ivar state: The state name, ex: CA or California. Note this should match the losing carrier’s information exactly. So if they spell out the entire state’s name instead of abbreviating it, please do so. + :ivar zip: The zip code, ex: 94105. + :ivar country: The country, ex: USA. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.street: Optional[str] = payload.get("street") + self.street_2: Optional[str] = payload.get("street_2") + self.city: Optional[str] = payload.get("city") + self.state: Optional[str] = payload.get("state") + self.zip: Optional[str] = payload.get("zip") + self.country: Optional[str] = payload.get("country") + + def to_dict(self): + return { + "street": self.street, + "street_2": self.street_2, + "city": self.city, + "state": self.state, + "zip": self.zip, + "country": self.country, + } + + class NumbersV1PortingLosingCarrierInformation(object): + """ + :ivar customer_name: Customer name as it is registered with the losing carrier. This can be an individual or a business name depending on the customer type selected. + :ivar account_number: The account number of the customer for the losing carrier. Only require for mobile phone numbers. + :ivar account_telephone_number: The account phone number of the customer for the losing carrier. + :ivar address_sid: If you already have an Address SID that represents the address needed for the LOA, you can provide an Address SID instead of providing the address object in the request body. This will copy the address into the port in request. If changes are made to the Address SID after port in request creation, those changes will not be reflected in the port in request. + :ivar address: + :ivar authorized_representative: The first and last name of the person listed with the losing carrier who is authorized to make changes on the account. + :ivar authorized_representative_email: Email address of the person (owner of the number) who will sign the letter of authorization for the port in request. This email address should belong to the person named in as the authorized representative. + :ivar customer_type: The type of customer account in the losing carrier. This should either be: 'Individual' or 'Business'. + :ivar authorized_representative_katakana: + :ivar sub_municipality: + :ivar building: + :ivar katakana_name: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_name: Optional[str] = payload.get("customer_name") + self.account_number: Optional[str] = payload.get("account_number") + self.account_telephone_number: Optional[str] = payload.get( + "account_telephone_number" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.address: Optional[PortingPortInList.NumbersV1PortingAddress] = ( + payload.get("address") + ) + self.authorized_representative: Optional[str] = payload.get( + "authorized_representative" + ) + self.authorized_representative_email: Optional[str] = payload.get( + "authorized_representative_email" + ) + self.customer_type: Optional["PortingPortInInstance.str"] = payload.get( + "customer_type" + ) + self.authorized_representative_katakana: Optional[str] = payload.get( + "authorized_representative_katakana" + ) + self.sub_municipality: Optional[str] = payload.get("sub_municipality") + self.building: Optional[str] = payload.get("building") + self.katakana_name: Optional[str] = payload.get("katakana_name") + + def to_dict(self): + return { + "customer_name": self.customer_name, + "account_number": self.account_number, + "account_telephone_number": self.account_telephone_number, + "address_sid": self.address_sid, + "address": self.address.to_dict() if self.address is not None else None, + "authorized_representative": self.authorized_representative, + "authorized_representative_email": self.authorized_representative_email, + "customer_type": self.customer_type, + "authorized_representative_katakana": self.authorized_representative_katakana, + "sub_municipality": self.sub_municipality, + "building": self.building, + "katakana_name": self.katakana_name, + } + + class NumbersV1PortingPortInCreate(object): + """ + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported + :ivar documents: List of document SIDs for all phone numbers included in the port in request. At least one document SID referring to a document of the type Utility Bill is required. + :ivar phone_numbers: List of phone numbers to be ported. Maximum of 1,000 phone numbers per request. + :ivar losing_carrier_information: + :ivar notification_emails: Additional emails to send a copy of the signed LOA to. + :ivar target_port_in_date: Target date to port the number. We cannot guarantee that this date will be honored by the other carriers, please work with Ops to get a confirmation of the firm order commitment (FOC) date. Expected format is ISO Local Date, example: ‘2011-12-03`. This date must be at least 7 days in the future for US ports and 10 days in the future for Japanese ports. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_start: The earliest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_end: The latest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar bundle_sid: The bundle sid is an optional identifier to reference a group of regulatory documents for a port request. + :ivar portability_advance_carrier: A field only required for Japan port in requests. It is a unique identifier for the donor carrier service the line is being ported from. + :ivar auto_cancel_approval_numbers: Japan specific field, indicates the number of phone numbers to automatically approve for cancellation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.account_sid: Optional[str] = payload.get("account_sid") + self.documents: Optional[List[str]] = payload.get("documents") + self.phone_numbers: Optional[ + List[PortingPortInList.NumbersV1PortingPortInCreatePhoneNumbers] + ] = payload.get("phone_numbers") + self.losing_carrier_information: Optional[ + PortingPortInList.NumbersV1PortingLosingCarrierInformation + ] = payload.get("losing_carrier_information") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.target_port_in_date: Optional[date] = payload.get( + "target_port_in_date" + ) + self.target_port_in_time_range_start: Optional[str] = payload.get( + "target_port_in_time_range_start" + ) + self.target_port_in_time_range_end: Optional[str] = payload.get( + "target_port_in_time_range_end" + ) + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.portability_advance_carrier: Optional[str] = payload.get( + "portability_advance_carrier" + ) + self.auto_cancel_approval_numbers: Optional[str] = payload.get( + "auto_cancel_approval_numbers" + ) + + def to_dict(self): + return { + "account_sid": self.account_sid, + "documents": self.documents, + "phone_numbers": ( + [phone_numbers.to_dict() for phone_numbers in self.phone_numbers] + if self.phone_numbers is not None + else None + ), + "losing_carrier_information": ( + self.losing_carrier_information.to_dict() + if self.losing_carrier_information is not None + else None + ), + "notification_emails": self.notification_emails, + "target_port_in_date": self.target_port_in_date, + "target_port_in_time_range_start": self.target_port_in_time_range_start, + "target_port_in_time_range_end": self.target_port_in_time_range_end, + "bundle_sid": self.bundle_sid, + "portability_advance_carrier": self.portability_advance_carrier, + "auto_cancel_approval_numbers": self.auto_cancel_approval_numbers, + } + + class NumbersV1PortingPortInCreatePhoneNumbers(object): + """ + :ivar phone_number: Phone number to be ported. This must be in the E164 Format. + :ivar pin: Some losing carriers require a PIN to authorize the port of a phone number. If the phone number is a US mobile phone number, the PIN is mandatory to process a porting request. Other carriers and number types may also require a PIN, you'll need to contact the losing carrier to determine what your phone number's PIN is. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.pin: Optional[str] = payload.get("pin") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "pin": self.pin, + } + def __init__(self, version: Version, port_in_request_sid: str): """ Initialize the PortingPortInContext @@ -157,6 +560,20 @@ def __init__(self, version: Version, port_in_request_sid: str): } self._uri = "/Porting/PortIn/{port_in_request_sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PortingPortInInstance @@ -164,9 +581,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 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: @@ -176,9 +615,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 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: @@ -188,17 +651,43 @@ def fetch(self) -> PortingPortInInstance: :returns: The fetched PortingPortInInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return PortingPortInInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], ) - return PortingPortInInstance( + 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: """ @@ -207,17 +696,27 @@ async def fetch_async(self) -> PortingPortInInstance: :returns: The fetched PortingPortInInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return PortingPortInInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], ) - return PortingPortInInstance( + 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: """ @@ -231,6 +730,179 @@ def __repr__(self) -> str: class PortingPortInList(ListResource): + class NumbersV1PortingAddress(object): + """ + :ivar street: The street address, ex: 101 Spear St + :ivar street_2: The building information, ex : 5th floor. + :ivar city: The city name, ex: San Francisco. + :ivar state: The state name, ex: CA or California. Note this should match the losing carrier’s information exactly. So if they spell out the entire state’s name instead of abbreviating it, please do so. + :ivar zip: The zip code, ex: 94105. + :ivar country: The country, ex: USA. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.street: Optional[str] = payload.get("street") + self.street_2: Optional[str] = payload.get("street_2") + self.city: Optional[str] = payload.get("city") + self.state: Optional[str] = payload.get("state") + self.zip: Optional[str] = payload.get("zip") + self.country: Optional[str] = payload.get("country") + + def to_dict(self): + return { + "street": self.street, + "street_2": self.street_2, + "city": self.city, + "state": self.state, + "zip": self.zip, + "country": self.country, + } + + class NumbersV1PortingLosingCarrierInformation(object): + """ + :ivar customer_name: Customer name as it is registered with the losing carrier. This can be an individual or a business name depending on the customer type selected. + :ivar account_number: The account number of the customer for the losing carrier. Only require for mobile phone numbers. + :ivar account_telephone_number: The account phone number of the customer for the losing carrier. + :ivar address_sid: If you already have an Address SID that represents the address needed for the LOA, you can provide an Address SID instead of providing the address object in the request body. This will copy the address into the port in request. If changes are made to the Address SID after port in request creation, those changes will not be reflected in the port in request. + :ivar address: + :ivar authorized_representative: The first and last name of the person listed with the losing carrier who is authorized to make changes on the account. + :ivar authorized_representative_email: Email address of the person (owner of the number) who will sign the letter of authorization for the port in request. This email address should belong to the person named in as the authorized representative. + :ivar customer_type: The type of customer account in the losing carrier. This should either be: 'Individual' or 'Business'. + :ivar authorized_representative_katakana: + :ivar sub_municipality: + :ivar building: + :ivar katakana_name: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_name: Optional[str] = payload.get("customer_name") + self.account_number: Optional[str] = payload.get("account_number") + self.account_telephone_number: Optional[str] = payload.get( + "account_telephone_number" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.address: Optional[PortingPortInList.NumbersV1PortingAddress] = ( + payload.get("address") + ) + self.authorized_representative: Optional[str] = payload.get( + "authorized_representative" + ) + self.authorized_representative_email: Optional[str] = payload.get( + "authorized_representative_email" + ) + self.customer_type: Optional["PortingPortInInstance.str"] = payload.get( + "customer_type" + ) + self.authorized_representative_katakana: Optional[str] = payload.get( + "authorized_representative_katakana" + ) + self.sub_municipality: Optional[str] = payload.get("sub_municipality") + self.building: Optional[str] = payload.get("building") + self.katakana_name: Optional[str] = payload.get("katakana_name") + + def to_dict(self): + return { + "customer_name": self.customer_name, + "account_number": self.account_number, + "account_telephone_number": self.account_telephone_number, + "address_sid": self.address_sid, + "address": self.address.to_dict() if self.address is not None else None, + "authorized_representative": self.authorized_representative, + "authorized_representative_email": self.authorized_representative_email, + "customer_type": self.customer_type, + "authorized_representative_katakana": self.authorized_representative_katakana, + "sub_municipality": self.sub_municipality, + "building": self.building, + "katakana_name": self.katakana_name, + } + + class NumbersV1PortingPortInCreate(object): + """ + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported + :ivar documents: List of document SIDs for all phone numbers included in the port in request. At least one document SID referring to a document of the type Utility Bill is required. + :ivar phone_numbers: List of phone numbers to be ported. Maximum of 1,000 phone numbers per request. + :ivar losing_carrier_information: + :ivar notification_emails: Additional emails to send a copy of the signed LOA to. + :ivar target_port_in_date: Target date to port the number. We cannot guarantee that this date will be honored by the other carriers, please work with Ops to get a confirmation of the firm order commitment (FOC) date. Expected format is ISO Local Date, example: ‘2011-12-03`. This date must be at least 7 days in the future for US ports and 10 days in the future for Japanese ports. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_start: The earliest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_end: The latest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar bundle_sid: The bundle sid is an optional identifier to reference a group of regulatory documents for a port request. + :ivar portability_advance_carrier: A field only required for Japan port in requests. It is a unique identifier for the donor carrier service the line is being ported from. + :ivar auto_cancel_approval_numbers: Japan specific field, indicates the number of phone numbers to automatically approve for cancellation. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.account_sid: Optional[str] = payload.get("account_sid") + self.documents: Optional[List[str]] = payload.get("documents") + self.phone_numbers: Optional[ + List[PortingPortInList.NumbersV1PortingPortInCreatePhoneNumbers] + ] = payload.get("phone_numbers") + self.losing_carrier_information: Optional[ + PortingPortInList.NumbersV1PortingLosingCarrierInformation + ] = payload.get("losing_carrier_information") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.target_port_in_date: Optional[date] = payload.get( + "target_port_in_date" + ) + self.target_port_in_time_range_start: Optional[str] = payload.get( + "target_port_in_time_range_start" + ) + self.target_port_in_time_range_end: Optional[str] = payload.get( + "target_port_in_time_range_end" + ) + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.portability_advance_carrier: Optional[str] = payload.get( + "portability_advance_carrier" + ) + self.auto_cancel_approval_numbers: Optional[str] = payload.get( + "auto_cancel_approval_numbers" + ) + + def to_dict(self): + return { + "account_sid": self.account_sid, + "documents": self.documents, + "phone_numbers": ( + [phone_numbers.to_dict() for phone_numbers in self.phone_numbers] + if self.phone_numbers is not None + else None + ), + "losing_carrier_information": ( + self.losing_carrier_information.to_dict() + if self.losing_carrier_information is not None + else None + ), + "notification_emails": self.notification_emails, + "target_port_in_date": self.target_port_in_date, + "target_port_in_time_range_start": self.target_port_in_time_range_start, + "target_port_in_time_range_end": self.target_port_in_time_range_end, + "bundle_sid": self.bundle_sid, + "portability_advance_carrier": self.portability_advance_carrier, + "auto_cancel_approval_numbers": self.auto_cancel_approval_numbers, + } + + class NumbersV1PortingPortInCreatePhoneNumbers(object): + """ + :ivar phone_number: Phone number to be ported. This must be in the E164 Format. + :ivar pin: Some losing carriers require a PIN to authorize the port of a phone number. If the phone number is a US mobile phone number, the PIN is mandatory to process a porting request. Other carriers and number types may also require a PIN, you'll need to contact the losing carrier to determine what your phone number's PIN is. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.phone_number: Optional[str] = payload.get("phone_number") + self.pin: Optional[str] = payload.get("pin") + + def to_dict(self): + return { + "phone_number": self.phone_number, + "pin": self.pin, + } + def __init__(self, version: Version): """ Initialize the PortingPortInList @@ -242,47 +914,109 @@ def __init__(self, version: 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, body: Union[object, object] = values.unset + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate ) -> PortingPortInInstance: """ Create the PortingPortInInstance - :param body: + :param numbers_v1_porting_port_in_create: :returns: The created PortingPortInInstance """ - data = body.to_dict() + payload, _, _ = self._create( + numbers_v1_porting_port_in_create=numbers_v1_porting_port_in_create + ) + return PortingPortInInstance(self._version, payload) + + def create_with_http_info( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> ApiResponse: + """ + Create the PortingPortInInstance and return response metadata + + :param numbers_v1_porting_port_in_create: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + numbers_v1_porting_port_in_create=numbers_v1_porting_port_in_create + ) + instance = PortingPortInInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = numbers_v1_porting_port_in_create.to_dict() headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Content-Type"] = "application/json" - payload = self._version.create( + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return PortingPortInInstance(self._version, payload) - async def create_async( - self, body: Union[object, object] = values.unset + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate ) -> PortingPortInInstance: """ Asynchronously create the PortingPortInInstance - :param body: + :param numbers_v1_porting_port_in_create: :returns: The created PortingPortInInstance """ - data = body.to_dict() + payload, _, _ = await self._create_async( + numbers_v1_porting_port_in_create=numbers_v1_porting_port_in_create + ) + return PortingPortInInstance(self._version, payload) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - headers["Content-Type"] = "application/json" + async def create_with_http_info_async( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> ApiResponse: + """ + Asynchronously create the PortingPortInInstance and return response metadata - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + :param numbers_v1_porting_port_in_create: - return PortingPortInInstance(self._version, payload) + :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: """ diff --git a/twilio/rest/numbers/v1/porting_port_in_phone_number.py b/twilio/rest/numbers/v1/porting_port_in_phone_number.py index f5d881a657..1efa19ebe8 100644 --- a/twilio/rest/numbers/v1/porting_port_in_phone_number.py +++ b/twilio/rest/numbers/v1/porting_port_in_phone_number.py @@ -14,7 +14,8 @@ 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,23 +24,24 @@ class PortingPortInPhoneNumberInstance(InstanceResource): """ - :ivar port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. - :ivar phone_number_sid: The SID of the Port In request phone number. This is a unique identifier of the phone number. - :ivar url: - :ivar account_sid: The SID of the account that the phone number belongs to. - :ivar phone_number_type: The type of the phone number. - :ivar date_created: The date when the phone number was created. - :ivar country: The country of the phone number. - :ivar missing_required_fields: The phone number is missing required fields. - :ivar last_updated: The timestamp when the status was last updated. - :ivar phone_number: The phone number. - :ivar portable: The phone number is portable. - :ivar not_portability_reason: The reason why the phone number is not portable. - :ivar not_portability_reason_code: The code of the reason why the phone number is not portable. - :ivar port_in_phone_number_status: The status of the phone number in the port in request. - :ivar port_out_pin: The pin required for the losing carrier to port out the phone number. - :ivar rejection_reason: The rejection reason returned by the vendor. - :ivar rejection_reason_code: The rejection reason code returned by the vendor. + :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__( @@ -84,11 +86,15 @@ def __init__( 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 @@ -125,6 +131,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PortingPortInPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PortingPortInPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "PortingPortInPhoneNumberInstance": """ Fetch the PortingPortInPhoneNumberInstance @@ -143,6 +167,24 @@ async def fetch_async(self) -> "PortingPortInPhoneNumberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PortingPortInPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PortingPortInPhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -176,6 +218,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PortingPortInPhoneNumberInstance @@ -183,9 +239,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 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: @@ -195,9 +273,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 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: @@ -207,18 +309,45 @@ def fetch(self) -> PortingPortInPhoneNumberInstance: :returns: The fetched PortingPortInPhoneNumberInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + 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"], ) - return PortingPortInPhoneNumberInstance( + 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: """ @@ -227,18 +356,29 @@ async def fetch_async(self) -> PortingPortInPhoneNumberInstance: :returns: The fetched PortingPortInPhoneNumberInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + 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"], ) - return PortingPortInPhoneNumberInstance( + 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: """ diff --git a/twilio/rest/numbers/v1/porting_portability.py b/twilio/rest/numbers/v1/porting_portability.py index d4f92ba7d5..5bcc0e604c 100644 --- a/twilio/rest/numbers/v1/porting_portability.py +++ b/twilio/rest/numbers/v1/porting_portability.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -30,11 +31,11 @@ class NumberType(object): """ :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: The target account sid to which the number will be ported - :ivar portable: Boolean flag specifying if phone number is portable or not. - :ivar pin_and_account_number_required: Boolean flag specifying if PIN and account number is required for the phone number. + :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. One of `22131`, `22132`, `22130`, `22133`, `22102` or `22135`. + :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. @@ -67,6 +68,7 @@ def __init__( self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[PortingPortabilityContext] = None @property @@ -85,31 +87,75 @@ def _proxy(self) -> "PortingPortabilityContext": return self._context def fetch( - self, target_account_sid: Union[str, object] = values.unset + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, ) -> "PortingPortabilityInstance": """ Fetch the PortingPortabilityInstance - :param target_account_sid: The SID of the account where the phone number(s) will be ported. + :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 + 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: The SID of the account where the phone number(s) will be ported. + :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: @@ -129,7 +175,7 @@ def __init__(self, version: Version, phone_number: str): Initialize the PortingPortabilityContext :param version: Version that contains the resource - :param phone_number: The phone number which portability is to be checked. Phone numbers are in E.164 format (e.g. +16175551212). + :param phone_number: Phone number to check portability in e164 format. """ super().__init__(version) @@ -141,58 +187,150 @@ def __init__(self, version: Version, phone_number: str): **self._solution ) - def fetch( - self, target_account_sid: Union[str, object] = values.unset - ) -> PortingPortabilityInstance: + def _fetch( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> tuple: """ - Fetch the PortingPortabilityInstance - - :param target_account_sid: The SID of the account where the phone number(s) will be ported. + Internal helper for fetch operation - :returns: The fetched PortingPortabilityInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "TargetAccountSid": target_account_sid, + "AddressSid": address_sid, } ) - 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, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> PortingPortabilityInstance: + """ + Fetch the PortingPortabilityInstance + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: The fetched PortingPortabilityInstance + """ + payload, _, _ = self._fetch( + target_account_sid=target_account_sid, address_sid=address_sid + ) return PortingPortabilityInstance( self._version, payload, phone_number=self._solution["phone_number"], ) - async def fetch_async( - self, target_account_sid: Union[str, object] = values.unset - ) -> PortingPortabilityInstance: + def fetch_with_http_info( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the PortingPortabilityInstance + Fetch the PortingPortabilityInstance and return response metadata - :param target_account_sid: The SID of the account where the phone number(s) will be ported. + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. - :returns: The fetched PortingPortabilityInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + target_account_sid=target_account_sid, address_sid=address_sid + ) + instance = PortingPortabilityInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "TargetAccountSid": target_account_sid, + "AddressSid": address_sid, } ) - 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, + 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 @@ -218,7 +356,7 @@ def get(self, phone_number: str) -> PortingPortabilityContext: """ Constructs a PortingPortabilityContext - :param phone_number: The phone number which portability is to be checked. Phone numbers are in E.164 format (e.g. +16175551212). + :param phone_number: Phone number to check portability in e164 format. """ return PortingPortabilityContext(self._version, phone_number=phone_number) @@ -226,7 +364,7 @@ def __call__(self, phone_number: str) -> PortingPortabilityContext: """ Constructs a PortingPortabilityContext - :param phone_number: The phone number which portability is to be checked. Phone numbers are in E.164 format (e.g. +16175551212). + :param phone_number: Phone number to check portability in e164 format. """ return PortingPortabilityContext(self._version, phone_number=phone_number) diff --git a/twilio/rest/numbers/v1/porting_webhook_configuration.py b/twilio/rest/numbers/v1/porting_webhook_configuration.py index ea6d9bd2eb..4769c6ae74 100644 --- a/twilio/rest/numbers/v1/porting_webhook_configuration.py +++ b/twilio/rest/numbers/v1/porting_webhook_configuration.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,9 +24,9 @@ class PortingWebhookConfigurationInstance(InstanceResource): """ :ivar url: The URL of the webhook configuration request - :ivar port_in_target_url: Webhook URL to send a request when a port in request or port in phone number event happens - :ivar port_out_target_url: Webhook URL to send a request when a port out phone number event happens - :ivar notifications_of: List of notification events to send a request to the webhook URL + :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]): @@ -59,6 +60,25 @@ def __init__(self, version: 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: @@ -69,17 +89,42 @@ def create( :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" - payload = self._version.create( + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return PortingWebhookConfigurationInstance(self._version, payload) - async def create_async( self, body: Union[object, object] = values.unset ) -> PortingWebhookConfigurationInstance: @@ -90,16 +135,22 @@ async def create_async( :returns: The created PortingWebhookConfigurationInstance """ - data = body.to_dict() + payload, _, _ = await self._create_async(body=body) + return PortingWebhookConfigurationInstance(self._version, payload) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - headers["Content-Type"] = "application/json" + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the PortingWebhookConfigurationInstance and return response metadata - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + :param body: - return PortingWebhookConfigurationInstance(self._version, payload) + :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: """ diff --git a/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py b/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py index beb011128f..e724498b0a 100644 --- a/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py +++ b/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py @@ -12,6 +12,8 @@ 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 @@ -29,7 +31,7 @@ def __init__( Initialize the PortingWebhookConfigurationDeleteContext :param version: Version that contains the resource - :param webhook_type: The of the webhook type of the configuration to be deleted + :param webhook_type: The webhook type for the configuration to be delete. `PORT_IN`, `PORT_OUT` """ super().__init__(version) @@ -41,6 +43,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PortingWebhookConfigurationDeleteInstance @@ -48,9 +64,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 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: @@ -60,10 +98,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 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: """ @@ -94,7 +140,7 @@ def get( """ Constructs a PortingWebhookConfigurationDeleteContext - :param webhook_type: The of the webhook type of the configuration to be deleted + :param webhook_type: The webhook type for the configuration to be delete. `PORT_IN`, `PORT_OUT` """ return PortingWebhookConfigurationDeleteContext( self._version, webhook_type=webhook_type @@ -106,7 +152,7 @@ def __call__( """ Constructs a PortingWebhookConfigurationDeleteContext - :param webhook_type: The of the webhook type of the configuration to be deleted + :param webhook_type: The webhook type for the configuration to be delete. `PORT_IN`, `PORT_OUT` """ return PortingWebhookConfigurationDeleteContext( self._version, webhook_type=webhook_type 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 index 541062ec6d..18e6f97003 100644 --- a/twilio/rest/numbers/v1/signing_request_configuration.py +++ b/twilio/rest/numbers/v1/signing_request_configuration.py @@ -12,12 +12,14 @@ Do not edit the class manually. """ -from typing import Any, Dict, Optional, Union +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): @@ -54,6 +56,28 @@ def __repr__(self) -> str: 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): @@ -67,6 +91,25 @@ def __init__(self, version: 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: @@ -77,17 +120,42 @@ def create( :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" - payload = self._version.create( + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return SigningRequestConfigurationInstance(self._version, payload) - async def create_async( self, body: Union[object, object] = values.unset ) -> SigningRequestConfigurationInstance: @@ -98,16 +166,457 @@ async def create_async( :returns: The created SigningRequestConfigurationInstance """ - data = body.to_dict() + 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["Content-Type"] = "application/json" - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers ) + return SigningRequestConfigurationPage(self._version, response) - return SigningRequestConfigurationInstance(self._version, payload) + 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: """ diff --git a/twilio/rest/numbers/v1/webhook.py b/twilio/rest/numbers/v1/webhook.py index 0986db12f3..c5c9783f7f 100644 --- a/twilio/rest/numbers/v1/webhook.py +++ b/twilio/rest/numbers/v1/webhook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,9 +25,9 @@ class WebhookInstance(InstanceResource): """ :ivar url: The URL of the webhook configuration request - :ivar port_in_target_url: Webhook URL to send a request when a port in request or port in phone number event happens - :ivar port_out_target_url: Webhook URL to send a request when a port out phone number event happens - :ivar notifications_of: List of notification events to send a request to the webhook URL + :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 """ @@ -68,34 +69,78 @@ def __init__(self, version: 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: """ - Asynchronously fetch the WebhookInstance + Fetch the WebhookInstance :returns: The fetched WebhookInstance """ - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + payload, _, _ = self._fetch() + return WebhookInstance(self._version, payload) - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata - return WebhookInstance(self._version, payload) - async def fetch_async(self) -> WebhookInstance: + :returns: ApiResponse with instance, status code, and headers """ - Asynchronously fetch the WebhookInstance + 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: The fetched WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.fetch_async( + headers["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 diff --git a/twilio/rest/numbers/v2/__init__.py b/twilio/rest/numbers/v2/__init__.py index 9b5b50154e..e4f3060250 100644 --- a/twilio/rest/numbers/v2/__init__.py +++ b/twilio/rest/numbers/v2/__init__.py @@ -15,8 +15,10 @@ 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 @@ -30,11 +32,19 @@ def __init__(self, domain: Domain): :param domain: The Twilio.numbers domain """ super().__init__(domain, "v2") + self._applications: Optional[ApplicationList] = None self._authorization_documents: Optional[AuthorizationDocumentList] = None self._bulk_hosted_number_orders: Optional[BulkHostedNumberOrderList] = None + self._bundle_clone: Optional[BundleCloneList] = None self._hosted_number_orders: Optional[HostedNumberOrderList] = None self._regulatory_compliance: Optional[RegulatoryComplianceList] = None + @property + def applications(self) -> ApplicationList: + if self._applications is None: + self._applications = ApplicationList(self) + return self._applications + @property def authorization_documents(self) -> AuthorizationDocumentList: if self._authorization_documents is None: @@ -47,6 +57,12 @@ def bulk_hosted_number_orders(self) -> BulkHostedNumberOrderList: 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: 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 index f56071878e..8956774fa8 100644 --- a/twilio/rest/numbers/v2/authorization_document/__init__.py +++ b/twilio/rest/numbers/v2/authorization_document/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AuthorizationDocumentContext] = None @property @@ -105,6 +107,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AuthorizationDocumentInstance": """ Fetch the AuthorizationDocumentInstance @@ -123,6 +143,24 @@ async def fetch_async(self) -> "AuthorizationDocumentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: """ @@ -163,6 +201,20 @@ def __init__(self, version: Version, sid: str): DependentHostedNumberOrderList ] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AuthorizationDocumentInstance @@ -170,9 +222,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 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: @@ -182,9 +256,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 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: @@ -194,17 +292,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: """ @@ -213,17 +337,27 @@ 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) @property def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: @@ -255,6 +389,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AuthorizationDocumentInstance :param payload: Payload response from the API """ + return AuthorizationDocumentInstance(self._version, payload) def __repr__(self) -> str: @@ -279,7 +414,7 @@ def __init__(self, version: Version): self._uri = "/HostedNumber/AuthorizationDocuments" - def create( + def _create( self, address_sid: str, email: str, @@ -287,18 +422,12 @@ def create( hosted_number_order_sids: List[str], contact_title: Union[str, object] = values.unset, cc_emails: Union[List[str], object] = values.unset, - ) -> AuthorizationDocumentInstance: + ) -> tuple: """ - Create the AuthorizationDocumentInstance + Internal helper for create operation - :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. - :param email: Email that this AuthorizationDocument will be sent to for signing. - :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. - :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. - :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. - :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. - - :returns: The created AuthorizationDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -315,13 +444,15 @@ def create( ) headers = values.of({"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 AuthorizationDocumentInstance(self._version, payload) - - async def create_async( + def create( self, address_sid: str, email: str, @@ -331,7 +462,7 @@ async def create_async( cc_emails: Union[List[str], object] = values.unset, ) -> AuthorizationDocumentInstance: """ - Asynchronously create the AuthorizationDocumentInstance + Create the AuthorizationDocumentInstance :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. :param email: Email that this AuthorizationDocument will be sent to for signing. @@ -342,6 +473,63 @@ async def create_async( :returns: The created AuthorizationDocumentInstance """ + payload, _, _ = self._create( + address_sid=address_sid, + email=email, + contact_phone_number=contact_phone_number, + hosted_number_order_sids=hosted_number_order_sids, + contact_title=contact_title, + cc_emails=cc_emails, + ) + return AuthorizationDocumentInstance(self._version, payload) + + def create_with_http_info( + self, + address_sid: str, + email: str, + contact_phone_number: str, + hosted_number_order_sids: List[str], + contact_title: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Create the AuthorizationDocumentInstance and return response metadata + + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + address_sid=address_sid, + email=email, + contact_phone_number=contact_phone_number, + hosted_number_order_sids=hosted_number_order_sids, + contact_title=contact_title, + cc_emails=cc_emails, + ) + instance = AuthorizationDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + address_sid: str, + email: str, + contact_phone_number: str, + hosted_number_order_sids: List[str], + contact_title: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -357,12 +545,77 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -423,6 +676,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AuthorizationDocumentInstance and returns headers from first page + + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + email=email, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams AuthorizationDocumentInstance and returns headers from first page + + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + email=email, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, email: Union[str, object] = values.unset, @@ -446,6 +759,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( email=email, @@ -478,6 +792,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -488,6 +803,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AuthorizationDocumentInstance and returns headers from first page + + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists AuthorizationDocumentInstance and returns headers from first page + + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, email: Union[str, object] = values.unset, @@ -518,7 +895,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( @@ -551,11 +934,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. diff --git a/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py b/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py index 7fc558fee2..eed80d038f 100644 --- a/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py +++ b/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -114,6 +115,7 @@ def get_instance( :param payload: Payload response from the API """ + return DependentHostedNumberOrderInstance( self._version, payload, @@ -231,6 +233,86 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union[ @@ -260,6 +342,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -300,6 +383,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -312,6 +396,84 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union[ @@ -350,8 +512,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, @@ -391,10 +561,118 @@ async def page_async( } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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 + ) + + 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, + } ) - return DependentHostedNumberOrderPage(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 = 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: """ @@ -406,7 +684,9 @@ def get_page(self, target_url: str) -> DependentHostedNumberOrderPage: :returns: Page of DependentHostedNumberOrderInstance """ response = self._version.domain.twilio.request("GET", target_url) - return DependentHostedNumberOrderPage(self._version, response, self._solution) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) async def get_page_async(self, target_url: str) -> DependentHostedNumberOrderPage: """ @@ -418,7 +698,9 @@ async def get_page_async(self, target_url: str) -> DependentHostedNumberOrderPag :returns: Page of DependentHostedNumberOrderInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return DependentHostedNumberOrderPage(self._version, response, self._solution) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) def __repr__(self) -> str: """ diff --git a/twilio/rest/numbers/v2/bulk_hosted_number_order.py b/twilio/rest/numbers/v2/bulk_hosted_number_order.py index 325ffe8e73..7ff4f50a40 100644 --- a/twilio/rest/numbers/v2/bulk_hosted_number_order.py +++ b/twilio/rest/numbers/v2/bulk_hosted_number_order.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -69,6 +70,7 @@ def __init__( self._solution = { "bulk_hosting_sid": bulk_hosting_sid or self.bulk_hosting_sid, } + self._context: Optional[BulkHostedNumberOrderContext] = None @property @@ -114,6 +116,34 @@ async def fetch_async( order_status=order_status, ) + def fetch_with_http_info( + self, order_status: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the BulkHostedNumberOrderInstance with HTTP info + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + order_status=order_status, + ) + + async def fetch_with_http_info_async( + self, order_status: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BulkHostedNumberOrderInstance with HTTP info + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + order_status=order_status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -143,6 +173,28 @@ def __init__(self, version: Version, bulk_hosting_sid: str): **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: @@ -153,19 +205,53 @@ def fetch( :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) + """ - data = values.of( + params = values.of( { "OrderStatus": order_status, } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + headers = values.of({}) - return BulkHostedNumberOrderInstance( - self._version, - payload, - bulk_hosting_sid=self._solution["bulk_hosting_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( @@ -178,22 +264,32 @@ async def fetch_async( :returns: The fetched BulkHostedNumberOrderInstance """ - - data = values.of( - { - "OrderStatus": order_status, - } + payload, _, _ = await self._fetch_async(order_status=order_status) + return BulkHostedNumberOrderInstance( + self._version, + payload, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + 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 - return 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: 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: """ @@ -218,6 +314,25 @@ def __init__(self, version: 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: @@ -228,17 +343,42 @@ def create( :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" - payload = self._version.create( + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) - return BulkHostedNumberOrderInstance(self._version, payload) - async def create_async( self, body: Union[object, object] = values.unset ) -> BulkHostedNumberOrderInstance: @@ -249,16 +389,22 @@ async def create_async( :returns: The created BulkHostedNumberOrderInstance """ - data = body.to_dict() + payload, _, _ = await self._create_async(body=body) + return BulkHostedNumberOrderInstance(self._version, payload) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - headers["Content-Type"] = "application/json" + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the BulkHostedNumberOrderInstance and return response metadata - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + :param body: - return BulkHostedNumberOrderInstance(self._version, payload) + :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: """ 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 index b2660cfc30..dce5e77367 100644 --- a/twilio/rest/numbers/v2/hosted_number_order.py +++ b/twilio/rest/numbers/v2/hosted_number_order.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,14 +26,20 @@ 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. @@ -53,6 +60,12 @@ class Status(object): :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__( @@ -89,10 +102,27 @@ def __init__( "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 @@ -128,6 +158,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "HostedNumberOrderInstance": """ Fetch the HostedNumberOrderInstance @@ -146,6 +194,108 @@ async def fetch_async(self) -> "HostedNumberOrderInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + def update( + self, + status: "HostedNumberOrderInstance.Status", + 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 @@ -163,7 +313,7 @@ def __init__(self, version: Version, sid: str): Initialize the HostedNumberOrderContext :param version: Version that contains the resource - :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. + :param sid: The SID of the HostedNumberOrder resource to update. """ super().__init__(version) @@ -173,6 +323,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/HostedNumber/Orders/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the HostedNumberOrderInstance @@ -180,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 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: @@ -192,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 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: @@ -204,17 +414,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: """ @@ -223,17 +459,185 @@ 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( + 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: """ @@ -253,6 +657,7 @@ def get_instance(self, payload: Dict[str, Any]) -> HostedNumberOrderInstance: :param payload: Payload response from the API """ + return HostedNumberOrderInstance(self._version, payload) def __repr__(self) -> str: @@ -277,7 +682,7 @@ def __init__(self, version: Version): self._uri = "/HostedNumber/Orders" - def create( + def _create( self, phone_number: str, contact_phone_number: str, @@ -295,28 +700,12 @@ def create( status_callback_method: Union[str, object] = values.unset, sms_application_sid: Union[str, object] = values.unset, contact_title: Union[str, object] = values.unset, - ) -> HostedNumberOrderInstance: + ) -> tuple: """ - Create the HostedNumberOrderInstance + Internal helper for create operation - :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 + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -341,13 +730,15 @@ def create( ) headers = values.of({"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 HostedNumberOrderInstance(self._version, payload) - - async def create_async( + def create( self, phone_number: str, contact_phone_number: str, @@ -367,7 +758,7 @@ async def create_async( contact_title: Union[str, object] = values.unset, ) -> HostedNumberOrderInstance: """ - Asynchronously create the HostedNumberOrderInstance + Create the HostedNumberOrderInstance :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. @@ -388,41 +779,273 @@ async def create_async( :returns: The created HostedNumberOrderInstance """ - - data = values.of( - { - "PhoneNumber": phone_number, - "ContactPhoneNumber": contact_phone_number, - "AddressSid": address_sid, - "Email": email, - "AccountSid": account_sid, - "FriendlyName": friendly_name, - "CcEmails": serialize.map(cc_emails, lambda e: e), - "SmsUrl": sms_url, - "SmsMethod": sms_method, - "SmsFallbackUrl": sms_fallback_url, - "SmsCapability": serialize.boolean_to_string(sms_capability), - "SmsFallbackMethod": sms_fallback_method, - "StatusCallbackUrl": status_callback_url, - "StatusCallbackMethod": status_callback_method, - "SmsApplicationSid": sms_application_sid, - "ContactTitle": contact_title, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + 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 stream( + def create_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, + 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, @@ -501,6 +1124,88 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams HostedNumberOrderInstance and returns headers from first page + + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams HostedNumberOrderInstance and returns headers from first page + + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union["HostedNumberOrderInstance.Status", object] = values.unset, @@ -530,6 +1235,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -571,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( @@ -584,6 +1291,86 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists HostedNumberOrderInstance and returns headers from first page + + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists HostedNumberOrderInstance and returns headers from first page + + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union["HostedNumberOrderInstance.Status", object] = values.unset, @@ -623,7 +1410,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( @@ -665,11 +1458,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, + 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. @@ -698,7 +1595,7 @@ def get(self, sid: str) -> HostedNumberOrderContext: """ Constructs a HostedNumberOrderContext - :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. + :param sid: The SID of the HostedNumberOrder resource to update. """ return HostedNumberOrderContext(self._version, sid=sid) @@ -706,7 +1603,7 @@ def __call__(self, sid: str) -> HostedNumberOrderContext: """ Constructs a HostedNumberOrderContext - :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. + :param sid: The SID of the HostedNumberOrder resource to update. """ return HostedNumberOrderContext(self._version, sid=sid) diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py index ccdcbb3f38..d917770b64 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -98,6 +99,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[BundleContext] = None @property @@ -133,6 +135,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BundleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BundleInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "BundleInstance": """ Fetch the BundleInstance @@ -151,6 +171,24 @@ async def fetch_async(self) -> "BundleInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BundleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BundleInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: Union["BundleInstance.Status", object] = values.unset, @@ -199,6 +237,54 @@ async def update_async( email=email, ) + def update_with_http_info( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the BundleInstance with HTTP info + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_with_http_info_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BundleInstance with HTTP info + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + @property def bundle_copies(self) -> BundleCopyList: """ @@ -259,6 +345,20 @@ def __init__(self, version: Version, sid: str): self._item_assignments: Optional[ItemAssignmentList] = None self._replace_items: Optional[ReplaceItemsList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the BundleInstance @@ -266,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: @@ -278,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: @@ -290,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: """ @@ -309,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, @@ -338,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, @@ -346,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, @@ -372,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: @@ -455,6 +735,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BundleInstance: :param payload: Payload response from the API """ + return BundleInstance(self._version, payload) def __repr__(self) -> str: @@ -479,7 +760,7 @@ def __init__(self, version: Version): self._uri = "/RegulatoryCompliance/Bundles" - def create( + def _create( self, friendly_name: str, email: str, @@ -488,19 +769,13 @@ 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( @@ -512,17 +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( + 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 BundleInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, email: str, @@ -531,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. @@ -541,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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + 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: Union[str, 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, @@ -588,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`. @@ -610,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, @@ -628,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, @@ -648,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`. @@ -670,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, @@ -685,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, @@ -707,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`. @@ -726,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, @@ -747,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, @@ -766,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`. @@ -785,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, @@ -804,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, @@ -826,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`. @@ -845,10 +1558,12 @@ def page( data = values.of( { "Status": status, + "BundleSids": bundle_sids, "FriendlyName": friendly_name, "RegulationSid": regulation_sid, "IsoCountry": iso_country, "NumberType": number_type, + "EndUserType": end_user_type, "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), "SortBy": sort_by, "SortDirection": sort_direction, @@ -861,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, @@ -886,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`. @@ -905,10 +1630,12 @@ async def page_async( data = values.of( { "Status": status, + "BundleSids": bundle_sids, "FriendlyName": friendly_name, "RegulationSid": regulation_sid, "IsoCountry": iso_country, "NumberType": number_type, + "EndUserType": end_user_type, "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), "SortBy": sort_by, "SortDirection": sort_direction, @@ -921,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 860a6f186e..d5f9d253c8 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -87,6 +88,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BundleCopyInstance: :param payload: Payload response from the API """ + return BundleCopyInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) @@ -120,15 +122,12 @@ def __init__(self, version: Version, bundle_sid: str): **self._solution ) - def create( - self, friendly_name: Union[str, object] = values.unset - ) -> BundleCopyInstance: + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: """ - Create the BundleCopyInstance - - :param friendly_name: The string that you assigned to describe the copied bundle. + Internal helper for create operation - :returns: The created BundleCopyInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -138,23 +137,53 @@ def create( ) headers = values.of({"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, friendly_name: Union[str, object] = values.unset + ) -> BundleCopyInstance: + """ + Create the BundleCopyInstance + + :param friendly_name: The string that you assigned to describe the copied bundle. + + :returns: The created BundleCopyInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name) return BundleCopyInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: Union[str, object] = values.unset - ) -> BundleCopyInstance: + ) -> ApiResponse: """ - Asynchronously create the BundleCopyInstance + Create the BundleCopyInstance and return response metadata :param friendly_name: The string that you assigned to describe the copied bundle. - :returns: The created BundleCopyInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -164,14 +193,47 @@ async def create_async( ) headers = values.of({"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, friendly_name: Union[str, object] = values.unset + ) -> BundleCopyInstance: + """ + Asynchronously create the BundleCopyInstance + + :param friendly_name: The string that you assigned to describe the copied bundle. + + :returns: The created BundleCopyInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return BundleCopyInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the BundleCopyInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the copied bundle. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -222,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, @@ -241,6 +353,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -267,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( @@ -275,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, @@ -299,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, @@ -326,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: """ @@ -341,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: """ @@ -353,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 83d061cda7..34107f1ca8 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -63,6 +64,7 @@ def __init__( "bundle_sid": bundle_sid, "sid": sid or self.sid, } + self._context: Optional[EvaluationContext] = None @property @@ -99,6 +101,24 @@ async def fetch_async(self) -> "EvaluationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EvaluationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EvaluationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -132,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 @@ -139,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: """ @@ -159,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: """ @@ -190,6 +264,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EvaluationInstance: :param payload: Payload response from the API """ + return EvaluationInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) @@ -223,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 @@ -230,33 +321,65 @@ def create(self) -> EvaluationInstance: :returns: The created EvaluationInstance """ + payload, _, _ = self._create() + return EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + def create_with_http_info(self) -> ApiResponse: + """ + Create the EvaluationInstance and return response metadata - payload = self._version.create(method="POST", uri=self._uri, headers=headers) - return EvaluationInstance( + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = EvaluationInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - async def create_async(self) -> EvaluationInstance: + async def _create_async(self) -> tuple: """ - Asynchronously create the EvaluationInstance - + Internal async helper for create operation - :returns: The created EvaluationInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( + 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: + """ + Asynchronously create the EvaluationInstance + + + :returns: The created EvaluationInstance + """ + payload, _, _ = await self._create_async() return EvaluationInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the EvaluationInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -307,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, @@ -326,6 +499,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -352,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( @@ -360,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, @@ -384,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, @@ -411,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: """ @@ -426,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: """ @@ -438,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 5fa77e7f95..336ee64979 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -54,6 +55,7 @@ def __init__( "bundle_sid": bundle_sid, "sid": sid or self.sid, } + self._context: Optional[ItemAssignmentContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ItemAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ItemAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ItemAssignmentInstance": """ Fetch the ItemAssignmentInstance @@ -108,6 +128,24 @@ async def fetch_async(self) -> "ItemAssignmentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ItemAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ItemAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,6 +179,20 @@ def __init__(self, version: Version, bundle_sid: str, sid: str): ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ItemAssignmentInstance @@ -148,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: @@ -160,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: @@ -172,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: """ @@ -192,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: """ @@ -223,6 +359,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ItemAssignmentInstance: :param payload: Payload response from the API """ + return ItemAssignmentInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) @@ -256,13 +393,12 @@ def __init__(self, version: Version, bundle_sid: str): **self._solution ) - def create(self, object_sid: str) -> ItemAssignmentInstance: + def _create(self, object_sid: str) -> tuple: """ - Create the ItemAssignmentInstance - - :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( @@ -272,21 +408,47 @@ def create(self, object_sid: str) -> ItemAssignmentInstance: ) headers = values.of({"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, 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( @@ -296,14 +458,41 @@ async def create_async(self, object_sid: str) -> ItemAssignmentInstance: ) headers = values.of({"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, 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, @@ -354,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, @@ -373,6 +612,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -399,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( @@ -407,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, @@ -431,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, @@ -458,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: """ @@ -473,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: """ @@ -485,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 2e2bc6c293..cb9c9a46dd 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -98,13 +99,12 @@ def __init__(self, version: Version, bundle_sid: str): **self._solution ) - def create(self, from_bundle_sid: str) -> ReplaceItemsInstance: + def _create(self, from_bundle_sid: str) -> tuple: """ - Create the ReplaceItemsInstance - - :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( @@ -114,21 +114,47 @@ def create(self, from_bundle_sid: str) -> ReplaceItemsInstance: ) headers = values.of({"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, 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( @@ -138,14 +164,43 @@ async def create_async(self, from_bundle_sid: str) -> ReplaceItemsInstance: ) headers = values.of({"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, 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 7886494d54..eaf2f958f2 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/end_user.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/end_user.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -60,6 +61,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EndUserContext] = None @property @@ -95,6 +97,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EndUserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EndUserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "EndUserInstance": """ Fetch the EndUserInstance @@ -113,6 +133,24 @@ async def fetch_async(self) -> "EndUserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -149,6 +187,42 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the EndUserInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the EndUserInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -176,6 +250,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/RegulatoryCompliance/EndUsers/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the EndUserInstance @@ -183,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: @@ -195,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: @@ -207,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: """ @@ -226,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, @@ -251,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, @@ -279,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: """ @@ -312,6 +554,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EndUserInstance: :param payload: Payload response from the API """ + return EndUserInstance(self._version, payload) def __repr__(self) -> str: @@ -336,20 +579,17 @@ def __init__(self, version: Version): self._uri = "/RegulatoryCompliance/EndUsers" - def create( + def _create( self, friendly_name: str, type: "EndUserInstance.Type", attributes: Union[object, object] = values.unset, - ) -> EndUserInstance: + ) -> tuple: """ - Create the EndUserInstance - - :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. + Internal helper for create operation - :returns: The created EndUserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -361,20 +601,22 @@ def create( ) headers = values.of({"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 EndUserInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, type: "EndUserInstance.Type", attributes: Union[object, object] = values.unset, ) -> EndUserInstance: """ - Asynchronously create the EndUserInstance + Create the EndUserInstance :param friendly_name: The string that you assigned to describe the resource. :param type: @@ -382,6 +624,44 @@ async def create_async( :returns: The created EndUserInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return EndUserInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Create the EndUserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = EndUserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -392,12 +672,55 @@ async def create_async( ) headers = values.of({"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, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronously create the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The created EndUserInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) return EndUserInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the EndUserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = EndUserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -448,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, @@ -467,6 +840,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -493,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( @@ -501,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, @@ -525,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( @@ -552,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 ba155575ac..cf6534bbed 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EndUserTypeContext] = None @property @@ -79,6 +81,24 @@ async def fetch_async(self) -> "EndUserTypeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -106,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 @@ -113,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: """ @@ -132,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: """ @@ -162,6 +234,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EndUserTypeInstance: :param payload: Payload response from the API """ + return EndUserTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -236,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, @@ -255,6 +378,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -281,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( @@ -289,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, @@ -313,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( @@ -340,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 706853bcee..88a84f8518 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/regulation.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/regulation.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -55,6 +56,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RegulationContext] = None @property @@ -100,6 +102,34 @@ async def fetch_async( include_constraints=include_constraints, ) + def fetch_with_http_info( + self, include_constraints: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the RegulationInstance with HTTP info + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + include_constraints=include_constraints, + ) + + async def fetch_with_http_info_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RegulationInstance with HTTP info + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + include_constraints=include_constraints, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -127,6 +157,28 @@ def __init__(self, version: Version, sid: str): } self._uri = "/RegulatoryCompliance/Regulations/{sid}".format(**self._solution) + def _fetch(self, include_constraints: Union[bool, object] = values.unset) -> 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: @@ -137,19 +189,55 @@ def fetch( :returns: The fetched RegulationInstance """ + payload, _, _ = self._fetch(include_constraints=include_constraints) + return RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) - data = values.of( + 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 + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "IncludeConstraints": serialize.boolean_to_string(include_constraints), } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + headers = values.of({}) - return RegulationInstance( - self._version, - payload, - sid=self._solution["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( @@ -162,22 +250,32 @@ async def fetch_async( :returns: The fetched RegulationInstance """ - - data = values.of( - { - "IncludeConstraints": serialize.boolean_to_string(include_constraints), - } + payload, _, _ = await self._fetch_async(include_constraints=include_constraints) + return RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + 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 - return RegulationInstance( + :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: """ @@ -197,6 +295,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RegulationInstance: :param payload: Payload response from the API """ + return RegulationInstance(self._version, payload) def __repr__(self) -> str: @@ -299,6 +398,82 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams RegulationInstance and returns headers from first page + + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams RegulationInstance and returns headers from first page + + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, @@ -326,6 +501,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end_user_type=end_user_type, @@ -364,6 +540,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -376,6 +553,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists RegulationInstance and returns headers from first page + + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists RegulationInstance and returns headers from first page + + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, @@ -412,7 +663,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 RegulationPage(self._version, response) async def page_async( @@ -451,11 +708,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 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 afa6579a13..abbddb13c1 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -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 @@ -190,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 @@ -197,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: @@ -209,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: @@ -221,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: """ @@ -240,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, @@ -265,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( @@ -295,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: """ @@ -330,6 +578,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentInstance: :param payload: Payload response from the API """ + return SupportingDocumentInstance(self._version, payload) def __repr__(self) -> str: @@ -354,20 +603,17 @@ def __init__(self, version: Version): self._uri = "/RegulatoryCompliance/SupportingDocuments" - def create( + def _create( self, friendly_name: str, type: str, attributes: Union[object, object] = values.unset, - ) -> SupportingDocumentInstance: + ) -> tuple: """ - Create the SupportingDocumentInstance - - :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. + Internal helper for create operation - :returns: The created SupportingDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -379,20 +625,22 @@ def create( ) headers = values.of({"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 SupportingDocumentInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, type: str, attributes: Union[object, object] = values.unset, ) -> SupportingDocumentInstance: """ - Asynchronously create the SupportingDocumentInstance + Create the SupportingDocumentInstance :param friendly_name: The string that you assigned to describe the resource. :param type: The type of the Supporting Document. @@ -400,6 +648,44 @@ async def create_async( :returns: The created SupportingDocumentInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return SupportingDocumentInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Create the SupportingDocumentInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = SupportingDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -410,12 +696,55 @@ async def create_async( ) headers = values.of({"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, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronously create the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: The created SupportingDocumentInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) return SupportingDocumentInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SupportingDocumentInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = SupportingDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -466,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, @@ -485,6 +864,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -511,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( @@ -519,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, @@ -543,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( @@ -570,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 0c7dc7b302..d2de945f94 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SupportingDocumentTypeContext] = None @property @@ -79,6 +81,24 @@ async def fetch_async(self) -> "SupportingDocumentTypeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -108,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 @@ -115,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: """ @@ -134,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: """ @@ -164,6 +236,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentTypeInstanc :param payload: Payload response from the API """ + return SupportingDocumentTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -238,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, @@ -257,6 +380,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -283,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( @@ -291,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, @@ -315,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( @@ -342,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/numbers/v3/__init__.py b/twilio/rest/numbers/v3/__init__.py new file mode 100644 index 0000000000..9826e176fb --- /dev/null +++ b/twilio/rest/numbers/v3/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.numbers.v3.hosted_number_order import HostedNumberOrderList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Numbers + + :param domain: The Twilio.numbers domain + """ + super().__init__(domain, "v3") + self._hosted_number_orders: Optional[HostedNumberOrderList] = None + + @property + def hosted_number_orders(self) -> HostedNumberOrderList: + if self._hosted_number_orders is None: + self._hosted_number_orders = HostedNumberOrderList(self) + return self._hosted_number_orders + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" 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 87cbbac248..b26f459963 100644 --- a/twilio/rest/oauth/OauthBase.py +++ b/twilio/rest/oauth/OauthBase.py @@ -14,6 +14,7 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.oauth.v1 import V1 +from twilio.rest.oauth.v2 import V2 class OauthBase(Domain): @@ -26,6 +27,7 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://oauth.twilio.com") self._v1: Optional[V1] = None + self._v2: Optional[V2] = None @property def v1(self) -> V1: @@ -36,6 +38,15 @@ def v1(self) -> V1: self._v1 = V1(self) return self._v1 + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Oauth + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/oauth/__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/authorize.py b/twilio/rest/oauth/v1/authorize.py index 19341db74e..69ff398da9 100644 --- a/twilio/rest/oauth/v1/authorize.py +++ b/twilio/rest/oauth/v1/authorize.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,22 +54,24 @@ def __init__(self, version: Version): self._uri = "/authorize" - def fetch( + def _fetch( self, response_type: Union[str, object] = values.unset, client_id: Union[str, object] = values.unset, redirect_uri: Union[str, object] = values.unset, scope: Union[str, object] = values.unset, state: Union[str, object] = values.unset, - ) -> AuthorizeInstance: + ) -> tuple: """ - Asynchronously fetch the AuthorizeInstance + Internal helper for fetch operation - :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback - :returns: The fetched AuthorizeInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Accept"] = "application/json" + params = values.of( { "ResponseType": response_type, @@ -79,13 +82,11 @@ def fetch( } ) - payload = self._version.fetch( + return self._version.fetch_with_response_info( method="GET", uri=self._uri, headers=headers, params=params ) - return AuthorizeInstance(self._version, payload) - - async def fetch_async( + def fetch( self, response_type: Union[str, object] = values.unset, client_id: Union[str, object] = values.unset, @@ -94,13 +95,62 @@ async def fetch_async( state: Union[str, object] = values.unset, ) -> AuthorizeInstance: """ - Asynchronously fetch the AuthorizeInstance + Fetch the AuthorizeInstance :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback :returns: The fetched AuthorizeInstance """ + payload, _, _ = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + return AuthorizeInstance(self._version, payload) + + def fetch_with_http_info( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the AuthorizeInstance and return response metadata + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Accept"] = "application/json" + params = values.of( { "ResponseType": response_type, @@ -111,12 +161,57 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( + return await self._version.fetch_with_response_info_async( method="GET", uri=self._uri, headers=headers, params=params ) + async def fetch_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: The fetched AuthorizeInstance + """ + payload, _, _ = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) return AuthorizeInstance(self._version, payload) + async def fetch_with_http_info_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously fetch the AuthorizeInstance and return response metadata + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + response_type=response_type, + client_id=client_id, + redirect_uri=redirect_uri, + scope=scope, + state=state, + ) + instance = AuthorizeInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/oauth/v1/token.py b/twilio/rest/oauth/v1/token.py index 0d5377a9f9..ebf53dc523 100644 --- a/twilio/rest/oauth/v1/token.py +++ b/twilio/rest/oauth/v1/token.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,7 +62,7 @@ def __init__(self, version: Version): self._uri = "/token" - def create( + def _create( self, grant_type: str, client_id: str, @@ -71,20 +72,12 @@ def create( audience: Union[str, object] = values.unset, refresh_token: Union[str, object] = values.unset, scope: Union[str, object] = values.unset, - ) -> TokenInstance: + ) -> tuple: """ - Create the TokenInstance - - :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. - :param client_id: A 34 character string that uniquely identifies this OAuth App. - :param client_secret: The credential for confidential OAuth App. - :param code: JWT token related to the authorization code grant type. - :param redirect_uri: The redirect uri - :param audience: The targeted audience uri - :param refresh_token: JWT token related to refresh access token. - :param scope: The scope of token + Internal helper for create operation - :returns: The created TokenInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -101,13 +94,15 @@ def create( ) headers = values.of({"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 TokenInstance(self._version, payload) - - async def create_async( + def create( self, grant_type: str, client_id: str, @@ -119,7 +114,7 @@ async def create_async( scope: Union[str, object] = values.unset, ) -> TokenInstance: """ - Asynchronously create the TokenInstance + Create the TokenInstance :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. :param client_id: A 34 character string that uniquely identifies this OAuth App. @@ -132,6 +127,73 @@ async def create_async( :returns: The created TokenInstance """ + payload, _, _ = self._create( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) + return TokenInstance(self._version, payload) + + def create_with_http_info( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the TokenInstance and return response metadata + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -147,12 +209,89 @@ async def create_async( ) headers = values.of({"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, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + payload, _, _ = await self._create_async( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) return TokenInstance(self._version, payload) + async def create_with_http_info_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TokenInstance and return response metadata + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + grant_type=grant_type, + client_id=client_id, + client_secret=client_secret, + code=code, + redirect_uri=redirect_uri, + audience=audience, + refresh_token=refresh_token, + scope=scope, + ) + instance = TokenInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/oauth/v2/__init__.py b/twilio/rest/oauth/v2/__init__.py new file mode 100644 index 0000000000..c061f851c4 --- /dev/null +++ b/twilio/rest/oauth/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + User OAuth API + User OAuth API + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.oauth.v2.authorize import AuthorizeList +from twilio.rest.oauth.v2.token import TokenList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Oauth + + :param domain: The Twilio.oauth domain + """ + super().__init__(domain, "v2") + self._authorize: Optional[AuthorizeList] = None + self._token: Optional[TokenList] = None + + @property + def authorize(self) -> AuthorizeList: + if self._authorize is None: + self._authorize = AuthorizeList(self) + return self._authorize + + @property + def token(self) -> TokenList: + if self._token is None: + self._token = TokenList(self) + return self._token + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" 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 6608a69a2c..dd8317b4c0 100644 --- a/twilio/rest/preview/PreviewBase.py +++ b/twilio/rest/preview/PreviewBase.py @@ -13,9 +13,7 @@ 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.wireless import Wireless @@ -29,21 +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._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: """ @@ -53,15 +40,6 @@ def hosted_numbers(self) -> HostedNumbers: self._hosted_numbers = HostedNumbers(self) return self._hosted_numbers - @property - def sync(self) -> Sync: - """ - :returns: Versions sync of Preview - """ - if self._sync is None: - self._sync = Sync(self) - return self._sync - @property def marketplace(self) -> Marketplace: """ diff --git a/twilio/rest/preview/__init__.py b/twilio/rest/preview/__init__.py index 79d870e134..c4658c62e3 100644 --- a/twilio/rest/preview/__init__.py +++ b/twilio/rest/preview/__init__.py @@ -1,28 +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.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: @@ -60,15 +50,6 @@ def installed_add_ons(self) -> InstalledAddOnList: ) return self.marketplace.installed_add_ons - @property - def services(self) -> ServiceList: - warn( - "services is deprecated. Use sync.services instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.sync.services - @property def commands(self) -> CommandList: warn( diff --git a/twilio/rest/preview/deployed_devices/fleet/__init__.py b/twilio/rest/preview/deployed_devices/fleet/__init__.py deleted file mode 100644 index f7321fdb2b..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/__init__.py +++ /dev/null @@ -1,674 +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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - 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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - 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 895bdc5682..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/certificate.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, 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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - 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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - 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 80f9f2372d..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/deployment.py +++ /dev/null @@ -1,630 +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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - 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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - 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 3cacc88f2b..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/device.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, 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 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": serialize.boolean_to_string(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": serialize.boolean_to_string(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": serialize.boolean_to_string(enabled), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - 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": serialize.boolean_to_string(enabled), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - 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 1b7c06e1f9..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/key.py +++ /dev/null @@ -1,646 +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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - 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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - 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/authorization_document/__init__.py b/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py index 79fe4beddd..27ff55c37d 100644 --- a/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py +++ b/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AuthorizationDocumentContext] = None @property @@ -105,6 +107,24 @@ async def fetch_async(self) -> "AuthorizationDocumentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, hosted_number_order_sids: Union[List[str], object] = values.unset, @@ -171,6 +191,72 @@ async def update_async( contact_phone_number=contact_phone_number, ) + def update_with_http_info( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the AuthorizationDocumentInstance with HTTP info + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + cc_emails=cc_emails, + status=status, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + ) + + async def update_with_http_info_async( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AuthorizationDocumentInstance with HTTP info + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + cc_emails=cc_emails, + status=status, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + ) + @property def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: """ @@ -211,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 @@ -218,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: """ @@ -237,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, @@ -258,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( @@ -285,18 +417,53 @@ def update( "ContactPhoneNumber": contact_phone_number, } ) + 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, + 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, @@ -305,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. @@ -317,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( @@ -332,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: """ @@ -375,6 +645,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AuthorizationDocumentInstance :param payload: Payload response from the API """ + return AuthorizationDocumentInstance(self._version, payload) def __repr__(self) -> str: @@ -399,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, @@ -407,18 +678,12 @@ def create( contact_title: str, contact_phone_number: str, cc_emails: Union[List[str], object] = values.unset, - ) -> AuthorizationDocumentInstance: + ) -> tuple: """ - Create the AuthorizationDocumentInstance - - :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. - :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. - :param email: Email that this AuthorizationDocument will be sent to for signing. - :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. - :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. - :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + Internal helper for create operation - :returns: The created AuthorizationDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -435,13 +700,15 @@ def create( ) headers = values.of({"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 AuthorizationDocumentInstance(self._version, payload) - - async def create_async( + def create( self, hosted_number_order_sids: List[str], address_sid: str, @@ -451,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. @@ -462,6 +729,63 @@ async def create_async( :returns: The created AuthorizationDocumentInstance """ + payload, _, _ = self._create( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + cc_emails=cc_emails, + ) + return AuthorizationDocumentInstance(self._version, payload) + + def create_with_http_info( + self, + hosted_number_order_sids: List[str], + address_sid: str, + email: str, + contact_title: str, + contact_phone_number: str, + cc_emails: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Create the AuthorizationDocumentInstance and return response metadata + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + cc_emails=cc_emails, + ) + instance = AuthorizationDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + hosted_number_order_sids: List[str], + address_sid: str, + email: str, + contact_title: str, + contact_phone_number: str, + cc_emails: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -477,12 +801,77 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -543,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, @@ -566,6 +1015,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( email=email, @@ -598,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( @@ -608,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, @@ -638,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( @@ -671,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. 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 35b67d71c7..1d52db3b65 100644 --- a/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py +++ b/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,6 +26,7 @@ class DependentHostedNumberOrderInstance(InstanceResource): class Status(object): + TWILIO_PROCESSING = "twilio-processing" RECEIVED = "received" PENDING_VERIFICATION = "pending-verification" VERIFIED = "verified" @@ -134,6 +136,7 @@ def get_instance( :param payload: Payload response from the API """ + return DependentHostedNumberOrderInstance( self._version, payload, @@ -257,6 +260,92 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, status: Union[ @@ -288,6 +377,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -331,6 +421,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -344,6 +435,90 @@ async def list_async( ) ] + def list_with_http_info( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DependentHostedNumberOrderInstance and returns headers from first page + + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, status: Union[ @@ -385,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, @@ -429,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: """ @@ -444,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: """ @@ -456,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 7010b1b3eb..1b26c1b53b 100644 --- a/twilio/rest/preview/hosted_numbers/hosted_number_order.py +++ b/twilio/rest/preview/hosted_numbers/hosted_number_order.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,6 +26,7 @@ class HostedNumberOrderInstance(InstanceResource): class Status(object): + TWILIO_PROCESSING = "twilio-processing" RECEIVED = "received" PENDING_VERIFICATION = "pending-verification" VERIFIED = "verified" @@ -113,6 +115,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[HostedNumberOrderContext] = None @property @@ -148,6 +151,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "HostedNumberOrderInstance": """ Fetch the HostedNumberOrderInstance @@ -166,6 +187,24 @@ async def fetch_async(self) -> "HostedNumberOrderInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -254,6 +293,94 @@ async def update_async( call_delay=call_delay, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the HostedNumberOrderInstance with HTTP info + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + unique_name=unique_name, + email=email, + cc_emails=cc_emails, + status=status, + verification_code=verification_code, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + extension=extension, + call_delay=call_delay, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance with HTTP info + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + unique_name=unique_name, + email=email, + cc_emails=cc_emails, + status=status, + verification_code=verification_code, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + extension=extension, + call_delay=call_delay, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -283,6 +410,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/HostedNumberOrders/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the HostedNumberOrderInstance @@ -290,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: @@ -302,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: @@ -314,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: """ @@ -333,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, @@ -359,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 + Internal helper for update operation - :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 + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -390,18 +604,64 @@ def update( "CallDelay": call_delay, } ) + 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, + 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, @@ -415,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. @@ -430,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, @@ -446,17 +745,111 @@ async def update_async( "CallDelay": call_delay, } ) + 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, + 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 @@ -477,6 +870,7 @@ def get_instance(self, payload: Dict[str, Any]) -> HostedNumberOrderInstance: :param payload: Payload response from the API """ + return HostedNumberOrderInstance(self._version, payload) def __repr__(self) -> str: @@ -501,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, @@ -546,6 +1000,122 @@ def create( :returns: The created HostedNumberOrderInstance """ + payload, _, _ = self._create( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + return HostedNumberOrderInstance(self._version, payload) + + def create_with_http_info( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the HostedNumberOrderInstance and return response metadata + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -570,12 +1140,14 @@ def create( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( + 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 ) - return HostedNumberOrderInstance(self._version, payload) - async def create_async( self, phone_number: str, @@ -599,7 +1171,73 @@ async def create_async( verification_document_sid: Union[str, object] = values.unset, ) -> HostedNumberOrderInstance: """ - Asynchronously create the HostedNumberOrderInstance + Asynchronously create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + + :returns: The created HostedNumberOrderInstance + """ + payload, _, _ = await self._create_async( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + ) + return HostedNumberOrderInstance(self._version, payload) + + async def create_with_http_info_async( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the HostedNumberOrderInstance and return response metadata :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. @@ -619,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": 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"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + phone_number=phone_number, + sms_capability=sms_capability, + account_sid=account_sid, + friendly_name=friendly_name, + unique_name=unique_name, + cc_emails=cc_emails, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + sms_application_sid=sms_application_sid, + address_sid=address_sid, + email=email, + verification_type=verification_type, + verification_document_sid=verification_document_sid, ) - - return HostedNumberOrderInstance(self._version, payload) + instance = HostedNumberOrderInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -735,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, @@ -764,6 +1476,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -805,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( @@ -818,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, @@ -857,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( @@ -899,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. diff --git a/twilio/rest/preview/marketplace/available_add_on/__init__.py b/twilio/rest/preview/marketplace/available_add_on/__init__.py index 7743d8a8c3..76fc06a367 100644 --- a/twilio/rest/preview/marketplace/available_add_on/__init__.py +++ b/twilio/rest/preview/marketplace/available_add_on/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AvailableAddOnContext] = None @property @@ -88,6 +90,24 @@ async def fetch_async(self) -> "AvailableAddOnInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def extensions(self) -> AvailableAddOnExtensionList: """ @@ -124,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 @@ -131,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: """ @@ -150,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: @@ -192,6 +264,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnInstance: :param payload: Payload response from the API """ + return AvailableAddOnInstance(self._version, payload) def __repr__(self) -> str: @@ -266,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, @@ -285,6 +408,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -311,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( @@ -319,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, @@ -343,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( @@ -370,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 d27b74cbfc..1d680e91c1 100644 --- a/twilio/rest/preview/marketplace/available_add_on/available_add_on_extension.py +++ b/twilio/rest/preview/marketplace/available_add_on/available_add_on_extension.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( "available_add_on_sid": available_add_on_sid, "sid": sid or self.sid, } + self._context: Optional[AvailableAddOnExtensionContext] = None @property @@ -87,6 +89,24 @@ async def fetch_async(self) -> "AvailableAddOnExtensionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -120,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 @@ -127,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: """ @@ -147,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: """ @@ -180,6 +254,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnExtensionInstan :param payload: Payload response from the API """ + return AvailableAddOnExtensionInstance( self._version, payload, @@ -265,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, @@ -284,6 +409,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -310,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( @@ -318,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, @@ -342,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, @@ -369,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 ) - return AvailableAddOnExtensionPage(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 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: """ @@ -384,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: """ @@ -396,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 731e84c80c..c7352ed699 100644 --- a/twilio/rest/preview/marketplace/installed_add_on/__init__.py +++ b/twilio/rest/preview/marketplace/installed_add_on/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[InstalledAddOnContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InstalledAddOnInstance": """ Fetch the InstalledAddOnInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "InstalledAddOnInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, configuration: Union[object, object] = values.unset, @@ -151,6 +189,42 @@ async def update_async( unique_name=unique_name, ) + def update_with_http_info( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the InstalledAddOnInstance with HTTP info + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + configuration=configuration, + unique_name=unique_name, + ) + + async def update_with_http_info_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnInstance with HTTP info + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + configuration=configuration, + unique_name=unique_name, + ) + @property def extensions(self) -> InstalledAddOnExtensionList: """ @@ -187,6 +261,20 @@ def __init__(self, version: Version, sid: str): self._extensions: Optional[InstalledAddOnExtensionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InstalledAddOnInstance @@ -194,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: @@ -206,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: @@ -218,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: """ @@ -237,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, @@ -262,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, @@ -290,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: @@ -335,6 +583,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnInstance: :param payload: Payload response from the API """ + return InstalledAddOnInstance(self._version, payload) def __repr__(self) -> str: @@ -359,22 +608,18 @@ def __init__(self, version: Version): self._uri = "/InstalledAddOns" - def create( + def _create( self, available_add_on_sid: str, accept_terms_of_service: bool, configuration: Union[object, object] = values.unset, unique_name: Union[str, object] = values.unset, - ) -> InstalledAddOnInstance: + ) -> tuple: """ - Create the InstalledAddOnInstance - - :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. + Internal helper for create operation - :returns: The created InstalledAddOnInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -389,13 +634,15 @@ def create( ) headers = values.of({"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 InstalledAddOnInstance(self._version, payload) - - async def create_async( + def create( self, available_add_on_sid: str, accept_terms_of_service: bool, @@ -403,7 +650,7 @@ async def create_async( unique_name: Union[str, object] = values.unset, ) -> InstalledAddOnInstance: """ - Asynchronously create the InstalledAddOnInstance + Create the InstalledAddOnInstance :param available_add_on_sid: The SID of the AvaliableAddOn to install. :param accept_terms_of_service: Whether the Terms of Service were accepted. @@ -412,6 +659,53 @@ async def create_async( :returns: The created InstalledAddOnInstance """ + payload, _, _ = self._create( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + return InstalledAddOnInstance(self._version, payload) + + def create_with_http_info( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the InstalledAddOnInstance and return response metadata + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + available_add_on_sid=available_add_on_sid, + accept_terms_of_service=accept_terms_of_service, + configuration=configuration, + unique_name=unique_name, + ) + instance = InstalledAddOnInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -425,12 +719,65 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -481,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, @@ -500,6 +897,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -526,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( @@ -534,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, @@ -558,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( @@ -585,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 f8e65d12c1..0c7f88938d 100644 --- a/twilio/rest/preview/marketplace/installed_add_on/installed_add_on_extension.py +++ b/twilio/rest/preview/marketplace/installed_add_on/installed_add_on_extension.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( "installed_add_on_sid": installed_add_on_sid, "sid": sid or self.sid, } + self._context: Optional[InstalledAddOnExtensionContext] = None @property @@ -89,6 +91,24 @@ async def fetch_async(self) -> "InstalledAddOnExtensionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, enabled: bool) -> "InstalledAddOnExtensionInstance": """ Update the InstalledAddOnExtensionInstance @@ -113,6 +133,30 @@ async def update_async(self, enabled: bool) -> "InstalledAddOnExtensionInstance" enabled=enabled, ) + def update_with_http_info(self, enabled: bool) -> ApiResponse: + """ + Update the InstalledAddOnExtensionInstance with HTTP info + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + enabled=enabled, + ) + + async def update_with_http_info_async(self, enabled: bool) -> ApiResponse: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance with HTTP info + + :param enabled: Whether the Extension should be invoked. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + enabled=enabled, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -146,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 @@ -153,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: """ @@ -173,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, @@ -186,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": 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, @@ -213,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": 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, @@ -240,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 @@ -260,6 +416,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnExtensionInstan :param payload: Payload response from the API """ + return InstalledAddOnExtensionInstance( self._version, payload, @@ -345,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, @@ -364,6 +571,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -390,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( @@ -398,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, @@ -422,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, @@ -449,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 ) - return InstalledAddOnExtensionPage(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 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: """ @@ -464,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: """ @@ -476,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 23f805a875..0000000000 --- a/twilio/rest/preview/sync/service/__init__.py +++ /dev/null @@ -1,709 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Preview - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page -from twilio.rest.preview.sync.service.document import DocumentList -from twilio.rest.preview.sync.service.sync_list import SyncListList -from twilio.rest.preview.sync.service.sync_map import SyncMapList - - -class ServiceInstance(InstanceResource): - """ - :ivar sid: - :ivar account_sid: - :ivar friendly_name: - :ivar date_created: - :ivar date_updated: - :ivar url: - :ivar webhook_url: - :ivar reachability_webhooks_enabled: - :ivar acl_enabled: - :ivar links: - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.account_sid: Optional[str] = payload.get("account_sid") - self.friendly_name: Optional[str] = payload.get("friendly_name") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.url: Optional[str] = payload.get("url") - self.webhook_url: Optional[str] = payload.get("webhook_url") - self.reachability_webhooks_enabled: Optional[bool] = payload.get( - "reachability_webhooks_enabled" - ) - self.acl_enabled: Optional[bool] = payload.get("acl_enabled") - self.links: Optional[Dict[str, object]] = payload.get("links") - - self._solution = { - "sid": sid or self.sid, - } - self._context: Optional[ServiceContext] = None - - @property - def _proxy(self) -> "ServiceContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: ServiceContext for this ServiceInstance - """ - if self._context is None: - self._context = ServiceContext( - self._version, - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "ServiceInstance": - """ - Fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "ServiceInstance": - """ - Asynchronous coroutine to fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - webhook_url: Union[str, object] = values.unset, - friendly_name: Union[str, object] = values.unset, - reachability_webhooks_enabled: Union[bool, object] = values.unset, - acl_enabled: Union[bool, object] = values.unset, - ) -> "ServiceInstance": - """ - Update the ServiceInstance - - :param webhook_url: - :param friendly_name: - :param reachability_webhooks_enabled: - :param acl_enabled: - - :returns: The updated ServiceInstance - """ - return self._proxy.update( - webhook_url=webhook_url, - friendly_name=friendly_name, - reachability_webhooks_enabled=reachability_webhooks_enabled, - acl_enabled=acl_enabled, - ) - - async def update_async( - self, - webhook_url: Union[str, object] = values.unset, - friendly_name: Union[str, object] = values.unset, - reachability_webhooks_enabled: Union[bool, object] = values.unset, - acl_enabled: Union[bool, object] = values.unset, - ) -> "ServiceInstance": - """ - Asynchronous coroutine to update the ServiceInstance - - :param webhook_url: - :param friendly_name: - :param reachability_webhooks_enabled: - :param acl_enabled: - - :returns: The updated ServiceInstance - """ - return await self._proxy.update_async( - webhook_url=webhook_url, - friendly_name=friendly_name, - reachability_webhooks_enabled=reachability_webhooks_enabled, - acl_enabled=acl_enabled, - ) - - @property - def documents(self) -> DocumentList: - """ - Access the documents - """ - return self._proxy.documents - - @property - def sync_lists(self) -> SyncListList: - """ - Access the sync_lists - """ - return self._proxy.sync_lists - - @property - def sync_maps(self) -> SyncMapList: - """ - Access the sync_maps - """ - return self._proxy.sync_maps - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".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": serialize.boolean_to_string( - reachability_webhooks_enabled - ), - "AclEnabled": serialize.boolean_to_string(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": serialize.boolean_to_string( - reachability_webhooks_enabled - ), - "AclEnabled": serialize.boolean_to_string(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": serialize.boolean_to_string( - reachability_webhooks_enabled - ), - "AclEnabled": serialize.boolean_to_string(acl_enabled), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ServiceInstance(self._version, payload) - - async def create_async( - self, - friendly_name: Union[str, object] = values.unset, - webhook_url: Union[str, object] = values.unset, - reachability_webhooks_enabled: Union[bool, object] = values.unset, - acl_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: - """ - Asynchronously create the ServiceInstance - - :param friendly_name: - :param webhook_url: - :param reachability_webhooks_enabled: - :param acl_enabled: - - :returns: The created ServiceInstance - """ - - data = values.of( - { - "FriendlyName": friendly_name, - "WebhookUrl": webhook_url, - "ReachabilityWebhooksEnabled": serialize.boolean_to_string( - reachability_webhooks_enabled - ), - "AclEnabled": serialize.boolean_to_string(acl_enabled), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ServiceInstance(self._version, payload) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[ServiceInstance]: - """ - Streams ServiceInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[ServiceInstance]: - """ - Asynchronously streams ServiceInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[ServiceInstance]: - """ - Lists ServiceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[ServiceInstance]: - """ - Asynchronously lists ServiceInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> ServicePage: - """ - Retrieve a single page of ServiceInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of ServiceInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - 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 c7033e2fd2..0000000000 --- a/twilio/rest/preview/sync/service/document/__init__.py +++ /dev/null @@ -1,657 +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), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DocumentInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - async def create_async( - self, - unique_name: Union[str, object] = values.unset, - data: Union[object, object] = values.unset, - ) -> DocumentInstance: - """ - Asynchronously create the DocumentInstance - - :param unique_name: - :param data: - - :returns: The created DocumentInstance - """ - - data = values.of( - { - "UniqueName": unique_name, - "Data": serialize.object(data), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return DocumentInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[DocumentInstance]: - """ - Streams DocumentInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[DocumentInstance]: - """ - Asynchronously streams DocumentInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DocumentInstance]: - """ - Lists DocumentInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[DocumentInstance]: - """ - Asynchronously lists DocumentInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> DocumentPage: - """ - Retrieve a single page of DocumentInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of DocumentInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - 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 48addbb163..0000000000 --- a/twilio/rest/preview/sync/service/document/document_permission.py +++ /dev/null @@ -1,593 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Preview - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class DocumentPermissionInstance(InstanceResource): - """ - :ivar account_sid: The unique SID identifier of the Twilio Account. - :ivar service_sid: The unique SID identifier of the Sync Service Instance. - :ivar document_sid: The unique SID identifier of the Sync Document to which the Permission applies. - :ivar identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - :ivar read: Boolean flag specifying whether the identity can read the Sync Document. - :ivar write: Boolean flag specifying whether the identity can update the Sync Document. - :ivar manage: Boolean flag specifying whether the identity can delete the Sync Document. - :ivar url: Contains an absolute URL for this Sync Document Permission. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - service_sid: str, - document_sid: str, - identity: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.service_sid: Optional[str] = payload.get("service_sid") - self.document_sid: Optional[str] = payload.get("document_sid") - self.identity: Optional[str] = payload.get("identity") - self.read: Optional[bool] = payload.get("read") - self.write: Optional[bool] = payload.get("write") - self.manage: Optional[bool] = payload.get("manage") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "service_sid": service_sid, - "document_sid": document_sid, - "identity": identity or self.identity, - } - self._context: Optional[DocumentPermissionContext] = None - - @property - def _proxy(self) -> "DocumentPermissionContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: DocumentPermissionContext for this DocumentPermissionInstance - """ - if self._context is None: - self._context = DocumentPermissionContext( - self._version, - service_sid=self._solution["service_sid"], - document_sid=self._solution["document_sid"], - identity=self._solution["identity"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the DocumentPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DocumentPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "DocumentPermissionInstance": - """ - Fetch the DocumentPermissionInstance - - - :returns: The fetched DocumentPermissionInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "DocumentPermissionInstance": - """ - Asynchronous coroutine to fetch the DocumentPermissionInstance - - - :returns: The fetched DocumentPermissionInstance - """ - return await self._proxy.fetch_async() - - def update( - self, read: bool, write: bool, manage: bool - ) -> "DocumentPermissionInstance": - """ - Update the DocumentPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync Document. - :param write: Boolean flag specifying whether the identity can update the Sync Document. - :param manage: Boolean flag specifying whether the identity can delete the Sync Document. - - :returns: The updated DocumentPermissionInstance - """ - return self._proxy.update( - read=read, - write=write, - manage=manage, - ) - - async def update_async( - self, read: bool, write: bool, manage: bool - ) -> "DocumentPermissionInstance": - """ - Asynchronous coroutine to update the DocumentPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync Document. - :param write: Boolean flag specifying whether the identity can update the Sync Document. - :param manage: Boolean flag specifying whether the identity can delete the Sync Document. - - :returns: The updated DocumentPermissionInstance - """ - return await self._proxy.update_async( - read=read, - write=write, - manage=manage, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".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": serialize.boolean_to_string(read), - "Write": serialize.boolean_to_string(write), - "Manage": serialize.boolean_to_string(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": serialize.boolean_to_string(read), - "Write": serialize.boolean_to_string(write), - "Manage": serialize.boolean_to_string(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 4b920e0194..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/__init__.py +++ /dev/null @@ -1,571 +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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncListInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - async def create_async( - self, unique_name: Union[str, object] = values.unset - ) -> SyncListInstance: - """ - Asynchronously create the SyncListInstance - - :param unique_name: - - :returns: The created SyncListInstance - """ - - data = values.of( - { - "UniqueName": unique_name, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncListInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[SyncListInstance]: - """ - Streams SyncListInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[SyncListInstance]: - """ - Asynchronously streams SyncListInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncListInstance]: - """ - Lists SyncListInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncListInstance]: - """ - Asynchronously lists SyncListInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncListPage: - """ - Retrieve a single page of SyncListInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - 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 b84411e8a8..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/sync_list_item.py +++ /dev/null @@ -1,725 +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), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - ) - - async def create_async(self, data: object) -> SyncListItemInstance: - """ - Asynchronously create the SyncListItemInstance - - :param data: - - :returns: The created SyncListItemInstance - """ - - data = values.of( - { - "Data": serialize.object(data), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - ) - - def stream( - self, - order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[SyncListItemInstance]: - """ - Streams SyncListItemInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param "SyncListItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncListItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page( - order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] - ) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[SyncListItemInstance]: - """ - Asynchronously streams SyncListItemInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param "SyncListItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncListItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async( - order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncListItemInstance]: - """ - Lists SyncListItemInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "SyncListItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncListItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - order=order, - from_=from_, - bounds=bounds, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncListItemInstance]: - """ - Asynchronously lists SyncListItemInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "SyncListItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncListItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - order=order, - from_=from_, - bounds=bounds, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncListItemPage: - """ - Retrieve a single page of SyncListItemInstance records from the API. - Request is executed immediately - - :param order: - :param from_: - :param bounds: - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncListItemInstance - """ - data = values.of( - { - "Order": order, - "From": from_, - "Bounds": bounds, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - 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 2fcaca5b26..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/sync_list_permission.py +++ /dev/null @@ -1,593 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Preview - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class SyncListPermissionInstance(InstanceResource): - """ - :ivar account_sid: The unique SID identifier of the Twilio Account. - :ivar service_sid: The unique SID identifier of the Sync Service Instance. - :ivar list_sid: The unique SID identifier of the Sync List to which the Permission applies. - :ivar identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - :ivar read: Boolean flag specifying whether the identity can read the Sync List and its Items. - :ivar write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync List. - :ivar manage: Boolean flag specifying whether the identity can delete the Sync List. - :ivar url: Contains an absolute URL for this Sync List Permission. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - service_sid: str, - list_sid: str, - identity: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.service_sid: Optional[str] = payload.get("service_sid") - self.list_sid: Optional[str] = payload.get("list_sid") - self.identity: Optional[str] = payload.get("identity") - self.read: Optional[bool] = payload.get("read") - self.write: Optional[bool] = payload.get("write") - self.manage: Optional[bool] = payload.get("manage") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "service_sid": service_sid, - "list_sid": list_sid, - "identity": identity or self.identity, - } - self._context: Optional[SyncListPermissionContext] = None - - @property - def _proxy(self) -> "SyncListPermissionContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: SyncListPermissionContext for this SyncListPermissionInstance - """ - if self._context is None: - self._context = SyncListPermissionContext( - self._version, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - identity=self._solution["identity"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the SyncListPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncListPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "SyncListPermissionInstance": - """ - Fetch the SyncListPermissionInstance - - - :returns: The fetched SyncListPermissionInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "SyncListPermissionInstance": - """ - Asynchronous coroutine to fetch the SyncListPermissionInstance - - - :returns: The fetched SyncListPermissionInstance - """ - return await self._proxy.fetch_async() - - def update( - self, read: bool, write: bool, manage: bool - ) -> "SyncListPermissionInstance": - """ - Update the SyncListPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync List. - :param write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync List. - :param manage: Boolean flag specifying whether the identity can delete the Sync List. - - :returns: The updated SyncListPermissionInstance - """ - return self._proxy.update( - read=read, - write=write, - manage=manage, - ) - - async def update_async( - self, read: bool, write: bool, manage: bool - ) -> "SyncListPermissionInstance": - """ - Asynchronous coroutine to update the SyncListPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync List. - :param write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync List. - :param manage: Boolean flag specifying whether the identity can delete the Sync List. - - :returns: The updated SyncListPermissionInstance - """ - return await self._proxy.update_async( - read=read, - write=write, - manage=manage, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".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": serialize.boolean_to_string(read), - "Write": serialize.boolean_to_string(write), - "Manage": serialize.boolean_to_string(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": serialize.boolean_to_string(read), - "Write": serialize.boolean_to_string(write), - "Manage": serialize.boolean_to_string(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 19c29f3267..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/__init__.py +++ /dev/null @@ -1,569 +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, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncMapInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - async def create_async( - self, unique_name: Union[str, object] = values.unset - ) -> SyncMapInstance: - """ - Asynchronously create the SyncMapInstance - - :param unique_name: - - :returns: The created SyncMapInstance - """ - - data = values.of( - { - "UniqueName": unique_name, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncMapInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[SyncMapInstance]: - """ - Streams SyncMapInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[SyncMapInstance]: - """ - Asynchronously streams SyncMapInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncMapInstance]: - """ - Lists SyncMapInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncMapInstance]: - """ - Asynchronously lists SyncMapInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncMapPage: - """ - Retrieve a single page of SyncMapInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - 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 78682fe588..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/sync_map_item.py +++ /dev/null @@ -1,729 +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), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - ) - - async def create_async(self, key: str, data: object) -> SyncMapItemInstance: - """ - Asynchronously create the SyncMapItemInstance - - :param key: - :param data: - - :returns: The created SyncMapItemInstance - """ - - data = values.of( - { - "Key": key, - "Data": serialize.object(data), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - ) - - def stream( - self, - order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[SyncMapItemInstance]: - """ - Streams SyncMapItemInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param "SyncMapItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncMapItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page( - order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] - ) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[SyncMapItemInstance]: - """ - Asynchronously streams SyncMapItemInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param "SyncMapItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncMapItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async( - order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncMapItemInstance]: - """ - Lists SyncMapItemInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "SyncMapItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncMapItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - order=order, - from_=from_, - bounds=bounds, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SyncMapItemInstance]: - """ - Asynchronously lists SyncMapItemInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "SyncMapItemInstance.QueryResultOrder" order: - :param str from_: - :param "SyncMapItemInstance.QueryFromBoundType" bounds: - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - order=order, - from_=from_, - bounds=bounds, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, - from_: Union[str, object] = values.unset, - bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> SyncMapItemPage: - """ - Retrieve a single page of SyncMapItemInstance records from the API. - Request is executed immediately - - :param order: - :param from_: - :param bounds: - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of SyncMapItemInstance - """ - data = values.of( - { - "Order": order, - "From": from_, - "Bounds": bounds, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - 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 b626f07bdc..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/sync_map_permission.py +++ /dev/null @@ -1,591 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Preview - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class SyncMapPermissionInstance(InstanceResource): - """ - :ivar account_sid: The unique SID identifier of the Twilio Account. - :ivar service_sid: The unique SID identifier of the Sync Service Instance. - :ivar map_sid: The unique SID identifier of the Sync Map to which the Permission applies. - :ivar identity: Arbitrary string identifier representing a human user associated with an FPA token, assigned by the developer. - :ivar read: Boolean flag specifying whether the identity can read the Sync Map and its Items. - :ivar write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync Map. - :ivar manage: Boolean flag specifying whether the identity can delete the Sync Map. - :ivar url: Contains an absolute URL for this Sync Map Permission. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - service_sid: str, - map_sid: str, - identity: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.service_sid: Optional[str] = payload.get("service_sid") - self.map_sid: Optional[str] = payload.get("map_sid") - self.identity: Optional[str] = payload.get("identity") - self.read: Optional[bool] = payload.get("read") - self.write: Optional[bool] = payload.get("write") - self.manage: Optional[bool] = payload.get("manage") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "service_sid": service_sid, - "map_sid": map_sid, - "identity": identity or self.identity, - } - self._context: Optional[SyncMapPermissionContext] = None - - @property - def _proxy(self) -> "SyncMapPermissionContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: SyncMapPermissionContext for this SyncMapPermissionInstance - """ - if self._context is None: - self._context = SyncMapPermissionContext( - self._version, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - identity=self._solution["identity"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the SyncMapPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncMapPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "SyncMapPermissionInstance": - """ - Fetch the SyncMapPermissionInstance - - - :returns: The fetched SyncMapPermissionInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "SyncMapPermissionInstance": - """ - Asynchronous coroutine to fetch the SyncMapPermissionInstance - - - :returns: The fetched SyncMapPermissionInstance - """ - return await self._proxy.fetch_async() - - def update( - self, read: bool, write: bool, manage: bool - ) -> "SyncMapPermissionInstance": - """ - Update the SyncMapPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync Map. - :param write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync Map. - :param manage: Boolean flag specifying whether the identity can delete the Sync Map. - - :returns: The updated SyncMapPermissionInstance - """ - return self._proxy.update( - read=read, - write=write, - manage=manage, - ) - - async def update_async( - self, read: bool, write: bool, manage: bool - ) -> "SyncMapPermissionInstance": - """ - Asynchronous coroutine to update the SyncMapPermissionInstance - - :param read: Boolean flag specifying whether the identity can read the Sync Map. - :param write: Boolean flag specifying whether the identity can create, update and delete Items of the Sync Map. - :param manage: Boolean flag specifying whether the identity can delete the Sync Map. - - :returns: The updated SyncMapPermissionInstance - """ - return await self._proxy.update_async( - read=read, - write=write, - manage=manage, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".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": serialize.boolean_to_string(read), - "Write": serialize.boolean_to_string(write), - "Manage": serialize.boolean_to_string(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": serialize.boolean_to_string(read), - "Write": serialize.boolean_to_string(write), - "Manage": serialize.boolean_to_string(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/wireless/command.py b/twilio/rest/preview/wireless/command.py index b91d1969e8..1ca73b5b3b 100644 --- a/twilio/rest/preview/wireless/command.py +++ b/twilio/rest/preview/wireless/command.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CommandContext] = None @property @@ -96,6 +98,24 @@ async def fetch_async(self) -> "CommandInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -123,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 @@ -130,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: """ @@ -149,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: """ @@ -179,6 +251,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: :param payload: Payload response from the API """ + return CommandInstance(self._version, payload) def __repr__(self) -> str: @@ -203,7 +276,7 @@ def __init__(self, version: Version): self._uri = "/Commands" - def create( + def _create( self, command: str, device: Union[str, object] = values.unset, @@ -212,19 +285,12 @@ def create( callback_url: Union[str, object] = values.unset, command_mode: Union[str, object] = values.unset, include_sid: Union[str, object] = values.unset, - ) -> CommandInstance: + ) -> tuple: """ - Create the CommandInstance + Internal helper for create operation - :param command: - :param device: - :param sim: - :param callback_method: - :param callback_url: - :param command_mode: - :param include_sid: - - :returns: The created CommandInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -240,13 +306,15 @@ def create( ) headers = values.of({"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 CommandInstance(self._version, payload) - - async def create_async( + def create( self, command: str, device: Union[str, object] = values.unset, @@ -257,7 +325,7 @@ async def create_async( include_sid: Union[str, object] = values.unset, ) -> CommandInstance: """ - Asynchronously create the CommandInstance + Create the CommandInstance :param command: :param device: @@ -269,6 +337,68 @@ async def create_async( :returns: The created CommandInstance """ + payload, _, _ = self._create( + command=command, + device=device, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + ) + return CommandInstance(self._version, payload) + + def create_with_http_info( + self, + command: str, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union[str, object] = values.unset, + include_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CommandInstance and return response metadata + + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + command=command, + device=device, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + ) + instance = CommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + command: str, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union[str, object] = values.unset, + include_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -283,12 +413,83 @@ async def create_async( ) headers = values.of({"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, + command: str, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union[str, object] = values.unset, + include_sid: Union[str, object] = values.unset, + ) -> CommandInstance: + """ + Asynchronously create the CommandInstance + + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: + + :returns: The created CommandInstance + """ + payload, _, _ = await self._create_async( + command=command, + device=device, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + ) return CommandInstance(self._version, payload) + async def create_with_http_info_async( + self, + command: str, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union[str, object] = values.unset, + include_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CommandInstance and return response metadata + + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + command=command, + device=device, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + ) + instance = CommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, device: Union[str, object] = values.unset, @@ -367,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, @@ -394,6 +671,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( device=device, @@ -432,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( @@ -444,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, @@ -480,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( @@ -519,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 b9ca020da6..46a4445e4d 100644 --- a/twilio/rest/preview/wireless/rate_plan.py +++ b/twilio/rest/preview/wireless/rate_plan.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -71,6 +72,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RatePlanContext] = None @property @@ -106,6 +108,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RatePlanInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RatePlanInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RatePlanInstance": """ Fetch the RatePlanInstance @@ -124,6 +144,24 @@ async def fetch_async(self) -> "RatePlanInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RatePlanInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RatePlanInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -160,6 +198,42 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RatePlanInstance with HTTP info + + :param unique_name: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RatePlanInstance with HTTP info + + :param unique_name: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -187,6 +261,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/RatePlans/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RatePlanInstance @@ -194,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: @@ -206,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: @@ -218,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: """ @@ -237,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, @@ -262,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, @@ -290,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: """ @@ -323,6 +567,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: :param payload: Payload response from the API """ + return RatePlanInstance(self._version, payload) def __repr__(self) -> str: @@ -347,7 +592,7 @@ def __init__(self, version: Version): self._uri = "/RatePlans" - def create( + def _create( self, unique_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -359,22 +604,12 @@ def create( commands_enabled: Union[bool, object] = values.unset, national_roaming_enabled: Union[bool, object] = values.unset, international_roaming: Union[List[str], object] = values.unset, - ) -> RatePlanInstance: + ) -> tuple: """ - Create the RatePlanInstance + Internal helper for create operation - :param unique_name: - :param friendly_name: - :param data_enabled: - :param data_limit: - :param data_metering: - :param messaging_enabled: - :param voice_enabled: - :param commands_enabled: - :param national_roaming_enabled: - :param international_roaming: - - :returns: The created RatePlanInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -397,13 +632,15 @@ def create( ) headers = values.of({"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 RatePlanInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -417,7 +654,7 @@ async def create_async( international_roaming: Union[List[str], object] = values.unset, ) -> RatePlanInstance: """ - Asynchronously create the RatePlanInstance + Create the RatePlanInstance :param unique_name: :param friendly_name: @@ -432,6 +669,83 @@ async def create_async( :returns: The created RatePlanInstance """ + payload, _, _ = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + commands_enabled=commands_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + ) + return RatePlanInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Create the RatePlanInstance and return response metadata + + :param unique_name: + :param friendly_name: + :param data_enabled: + :param data_limit: + :param data_metering: + :param messaging_enabled: + :param voice_enabled: + :param commands_enabled: + :param national_roaming_enabled: + :param international_roaming: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + commands_enabled=commands_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + ) + instance = RatePlanInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -453,12 +767,101 @@ async def create_async( ) headers = values.of({"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, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronously create the RatePlanInstance + + :param unique_name: + :param friendly_name: + :param data_enabled: + :param data_limit: + :param data_metering: + :param messaging_enabled: + :param voice_enabled: + :param commands_enabled: + :param national_roaming_enabled: + :param international_roaming: + + :returns: The created RatePlanInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + commands_enabled=commands_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + ) return RatePlanInstance(self._version, payload) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the RatePlanInstance and return response metadata + + :param unique_name: + :param friendly_name: + :param data_enabled: + :param data_limit: + :param data_metering: + :param messaging_enabled: + :param voice_enabled: + :param commands_enabled: + :param national_roaming_enabled: + :param international_roaming: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + commands_enabled=commands_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + ) + instance = RatePlanInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -509,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, @@ -528,6 +981,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -554,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( @@ -562,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, @@ -586,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( @@ -613,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 8620c03ba2..ac6b78788d 100644 --- a/twilio/rest/preview/wireless/sim/__init__.py +++ b/twilio/rest/preview/wireless/sim/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -86,6 +87,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SimContext] = None @property @@ -121,6 +123,24 @@ async def fetch_async(self) -> "SimInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -241,6 +261,126 @@ async def update_async( voice_url=voice_url, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SimInstance with HTTP info + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance with HTTP info + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) + @property def usage(self) -> UsageList: """ @@ -277,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 @@ -284,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: """ @@ -303,17 +485,83 @@ 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, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + "RatePlan": rate_plan, + "Status": status, + "CommandsCallbackMethod": commands_callback_method, + "CommandsCallbackUrl": commands_callback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) def update( self, @@ -356,6 +604,114 @@ def update( :returns: The updated SimInstance """ + payload, _, _ = self._update( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SimInstance and return response metadata + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "UniqueName": unique_name, @@ -376,14 +732,15 @@ 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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) async def update_async( self, @@ -426,34 +783,87 @@ async def update_async( :returns: The updated SimInstance """ - data = values.of( - { - "UniqueName": unique_name, - "CallbackMethod": callback_method, - "CallbackUrl": callback_url, - "FriendlyName": friendly_name, - "RatePlan": rate_plan, - "Status": status, - "CommandsCallbackMethod": commands_callback_method, - "CommandsCallbackUrl": commands_callback_url, - "SmsFallbackMethod": sms_fallback_method, - "SmsFallbackUrl": sms_fallback_url, - "SmsMethod": sms_method, - "SmsUrl": sms_url, - "VoiceFallbackMethod": voice_fallback_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceMethod": voice_method, - "VoiceUrl": voice_url, - } + payload, _, _ = await self._update_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, ) + 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 - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + :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: - return SimInstance(self._version, payload, sid=self._solution["sid"]) + :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: @@ -485,6 +895,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SimInstance: :param payload: Payload response from the API """ + return SimInstance(self._version, payload) def __repr__(self) -> str: @@ -593,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, @@ -622,6 +1115,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -663,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( @@ -676,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, @@ -715,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( @@ -757,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 d90b5f9e84..33010acf35 100644 --- a/twilio/rest/preview/wireless/sim/usage.py +++ b/twilio/rest/preview/wireless/sim/usage.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -49,6 +50,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): self._solution = { "sim_sid": sim_sid, } + self._context: Optional[UsageContext] = None @property @@ -102,6 +104,42 @@ async def fetch_async( start=start, ) + def fetch_with_http_info( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the UsageInstance with HTTP info + + :param end: + :param start: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + end=end, + start=start, + ) + + async def fetch_with_http_info_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the UsageInstance with HTTP info + + :param end: + :param start: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + end=end, + start=start, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -129,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 + Internal helper for fetch operation - :param end: - :param start: - - :returns: The fetched UsageInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "End": end, "Start": start, } ) - 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) + + async def _fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "End": end, "Start": start, } ) - 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 diff --git a/twilio/rest/preview_iam/PreviewIamBase.py b/twilio/rest/preview_iam/PreviewIamBase.py new file mode 100644 index 0000000000..22fcbe70b1 --- /dev/null +++ b/twilio/rest/preview_iam/PreviewIamBase.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.preview_iam.v1 import V1 + + +class PreviewIamBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the PreviewIam Domain + + :returns: Domain for PreviewIam + """ + super().__init__(twilio, "https://preview-iam.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of PreviewIam + """ + 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/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/preview_iam/v1/__init__.py b/twilio/rest/preview_iam/v1/__init__.py new file mode 100644 index 0000000000..2243277793 --- /dev/null +++ b/twilio/rest/preview_iam/v1/__init__.py @@ -0,0 +1,51 @@ +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.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 PreviewIam + + :param domain: The Twilio.preview_iam domain + """ + super().__init__(domain, "v1") + 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/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/preview_messaging/__init__.py b/twilio/rest/preview_messaging/__init__.py deleted file mode 100644 index 73bf67969d..0000000000 --- a/twilio/rest/preview_messaging/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -from twilio.rest.preview_messaging.PreviewMessagingBase import PreviewMessagingBase -from twilio.rest.preview_messaging.v1.broadcast import BroadcastList -from twilio.rest.preview_messaging.v1.message import MessageList - - -class PreviewMessaging(PreviewMessagingBase): - @property - def broadcast(self) -> BroadcastList: - return self.v1.broadcasts - - @property - def messages(self) -> MessageList: - return self.v1.messages diff --git a/twilio/rest/pricing/v1/messaging/country.py b/twilio/rest/pricing/v1/messaging/country.py index 47f5707ce8..ecb387919d 100644 --- a/twilio/rest/pricing/v1/messaging/country.py +++ b/twilio/rest/pricing/v1/messaging/country.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -86,6 +88,24 @@ async def fetch_async(self) -> "CountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -113,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 @@ -120,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: """ @@ -139,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: """ @@ -169,6 +241,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -243,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, @@ -262,6 +385,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -288,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( @@ -296,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, @@ -320,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( @@ -347,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/country.py b/twilio/rest/pricing/v1/phone_number/country.py index b0822fff23..7775696a6d 100644 --- a/twilio/rest/pricing/v1/phone_number/country.py +++ b/twilio/rest/pricing/v1/phone_number/country.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -49,6 +50,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -84,6 +86,24 @@ async def fetch_async(self) -> "CountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -111,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 @@ -118,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: """ @@ -137,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: """ @@ -167,6 +239,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -241,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, @@ -260,6 +383,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -286,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( @@ -294,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, @@ -318,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( @@ -345,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/country.py b/twilio/rest/pricing/v1/voice/country.py index e3b1496de4..600488ab44 100644 --- a/twilio/rest/pricing/v1/voice/country.py +++ b/twilio/rest/pricing/v1/voice/country.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -88,6 +90,24 @@ async def fetch_async(self) -> "CountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -115,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 @@ -122,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: """ @@ -141,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: """ @@ -171,6 +243,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -245,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, @@ -264,6 +387,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -290,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( @@ -298,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, @@ -322,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( @@ -349,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 910919707e..5dab5e2dd0 100644 --- a/twilio/rest/pricing/v1/voice/number.py +++ b/twilio/rest/pricing/v1/voice/number.py @@ -13,6 +13,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 @@ -46,6 +48,7 @@ def __init__( self._solution = { "number": number or self.number, } + self._context: Optional[NumberContext] = None @property @@ -81,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 @@ -108,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 @@ -115,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: """ @@ -134,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: """ diff --git a/twilio/rest/pricing/v2/country.py b/twilio/rest/pricing/v2/country.py index a058c071b5..94cdd8a272 100644 --- a/twilio/rest/pricing/v2/country.py +++ b/twilio/rest/pricing/v2/country.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -88,6 +90,24 @@ async def fetch_async(self) -> "CountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -115,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 @@ -122,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: """ @@ -141,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: """ @@ -171,6 +243,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -245,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, @@ -264,6 +387,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -290,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( @@ -298,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, @@ -322,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( @@ -349,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 6c4cd9fe9d..eddd2b6ef5 100644 --- a/twilio/rest/pricing/v2/number.py +++ b/twilio/rest/pricing/v2/number.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( self._solution = { "destination_number": destination_number or self.destination_number, } + self._context: Optional[NumberContext] = None @property @@ -101,6 +103,34 @@ async def fetch_async( origination_number=origination_number, ) + def fetch_with_http_info( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the NumberInstance with HTTP info + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + origination_number=origination_number, + ) + + async def fetch_with_http_info_async( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NumberInstance with HTTP info + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + origination_number=origination_number, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -128,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: @@ -138,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( @@ -163,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: """ diff --git a/twilio/rest/pricing/v2/voice/country.py b/twilio/rest/pricing/v2/voice/country.py index 4a84bbd734..303e8d8522 100644 --- a/twilio/rest/pricing/v2/voice/country.py +++ b/twilio/rest/pricing/v2/voice/country.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -88,6 +90,24 @@ async def fetch_async(self) -> "CountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -115,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 @@ -122,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: """ @@ -141,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: """ @@ -171,6 +243,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -245,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, @@ -264,6 +387,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -290,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( @@ -298,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, @@ -322,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( @@ -349,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 6dd8764821..516e6f4cb4 100644 --- a/twilio/rest/pricing/v2/voice/number.py +++ b/twilio/rest/pricing/v2/voice/number.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -54,6 +55,7 @@ def __init__( self._solution = { "destination_number": destination_number or self.destination_number, } + self._context: Optional[NumberContext] = None @property @@ -99,6 +101,34 @@ async def fetch_async( origination_number=origination_number, ) + def fetch_with_http_info( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the NumberInstance with HTTP info + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + origination_number=origination_number, + ) + + async def fetch_with_http_info_async( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NumberInstance with HTTP info + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + origination_number=origination_number, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -126,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: @@ -136,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( @@ -161,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: """ diff --git a/twilio/rest/proxy/v1/service/__init__.py b/twilio/rest/proxy/v1/service/__init__.py index 7337294a6c..82b845dfb5 100644 --- a/twilio/rest/proxy/v1/service/__init__.py +++ b/twilio/rest/proxy/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -22,7 +23,6 @@ from twilio.base.page import Page from twilio.rest.proxy.v1.service.phone_number import PhoneNumberList from twilio.rest.proxy.v1.service.session import SessionList -from twilio.rest.proxy.v1.service.short_code import ShortCodeList class ServiceInstance(InstanceResource): @@ -91,6 +91,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -126,6 +127,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -144,6 +163,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -220,6 +257,82 @@ async def update_async( chat_instance_sid=chat_instance_sid, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + @property def phone_numbers(self) -> PhoneNumberList: """ @@ -234,13 +347,6 @@ def sessions(self) -> SessionList: """ return self._proxy.sessions - @property - def short_codes(self) -> ShortCodeList: - """ - Access the short_codes - """ - return self._proxy.short_codes - def __repr__(self) -> str: """ Provide a friendly representation @@ -270,7 +376,20 @@ def __init__(self, version: Version, sid: str): self._phone_numbers: Optional[PhoneNumberList] = None self._sessions: Optional[SessionList] = None - self._short_codes: Optional[ShortCodeList] = None + + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) def delete(self) -> bool: """ @@ -279,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: @@ -291,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: @@ -303,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: """ @@ -322,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, @@ -346,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/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. - :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + Internal helper for update operation - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "UniqueName": unique_name, @@ -373,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, @@ -396,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. @@ -409,6 +604,78 @@ async def update_async( :returns: The updated ServiceInstance """ + payload, _, _ = self._update( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "UniqueName": unique_name, @@ -421,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, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + headers["Accept"] = "application/json" - @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 + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def sessions(self) -> SessionList: - """ - Access the sessions - """ - if self._sessions is None: - self._sessions = SessionList( - self._version, - self._solution["sid"], - ) - return self._sessions + 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: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) @property - def short_codes(self) -> ShortCodeList: + def phone_numbers(self) -> PhoneNumberList: """ - Access the short_codes + Access the phone_numbers """ - if self._short_codes is None: - self._short_codes = ShortCodeList( + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList( self._version, self._solution["sid"], ) - return self._short_codes + 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._sessions def __repr__(self) -> str: """ @@ -484,6 +819,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -508,7 +844,7 @@ def __init__(self, version: Version): self._uri = "/Services" - def create( + def _create( self, unique_name: str, default_ttl: Union[int, object] = values.unset, @@ -520,20 +856,12 @@ def create( intercept_callback_url: Union[str, object] = values.unset, out_of_session_callback_url: Union[str, object] = values.unset, chat_instance_sid: Union[str, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Create the ServiceInstance + Internal helper for create operation - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** - :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. - :param callback_url: The URL we should call when the interaction status changes. - :param geo_match_level: - :param number_selection_behavior: - :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. - :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. - :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. - - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -550,13 +878,15 @@ def create( ) headers = values.of({"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 ServiceInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: str, default_ttl: Union[int, object] = values.unset, @@ -570,7 +900,7 @@ async def create_async( chat_instance_sid: Union[str, object] = values.unset, ) -> ServiceInstance: """ - Asynchronously create the ServiceInstance + Create the ServiceInstance :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. @@ -583,6 +913,77 @@ async def create_async( :returns: The created ServiceInstance """ + payload, _, _ = self._create( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -598,12 +999,93 @@ async def create_async( ) headers = values.of({"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, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) return ServiceInstance(self._version, payload) + async def create_with_http_info_async( + self, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -654,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, @@ -673,6 +1205,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -699,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( @@ -707,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, @@ -731,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( @@ -758,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 05b9033602..8d206f2e06 100644 --- a/twilio/rest/proxy/v1/service/phone_number.py +++ b/twilio/rest/proxy/v1/service/phone_number.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[PhoneNumberContext] = None @property @@ -104,6 +106,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "PhoneNumberInstance": """ Fetch the PhoneNumberInstance @@ -122,6 +142,24 @@ async def fetch_async(self) -> "PhoneNumberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, is_reserved: Union[bool, object] = values.unset ) -> "PhoneNumberInstance": @@ -150,6 +188,34 @@ async def update_async( is_reserved=is_reserved, ) + def update_with_http_info( + self, is_reserved: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Update the PhoneNumberInstance with HTTP info + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + is_reserved=is_reserved, + ) + + async def update_with_http_info_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PhoneNumberInstance with HTTP info + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + is_reserved=is_reserved, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -181,6 +247,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PhoneNumberInstance @@ -188,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: @@ -200,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: @@ -212,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: """ @@ -232,12 +385,7 @@ 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, @@ -245,28 +393,56 @@ async def fetch_async(self) -> PhoneNumberInstance: sid=self._solution["sid"], ) - def update( - self, is_reserved: Union[bool, object] = values.unset - ) -> PhoneNumberInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the PhoneNumberInstance + Asynchronous coroutine to fetch the PhoneNumberInstance and return response metadata - :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - :returns: The updated PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = await self._fetch_async() + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, is_reserved: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "IsReserved": serialize.boolean_to_string(is_reserved), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> PhoneNumberInstance: + """ + Update the PhoneNumberInstance + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated PhoneNumberInstance + """ + payload, _, _ = self._update(is_reserved=is_reserved) return PhoneNumberInstance( self._version, payload, @@ -274,28 +450,61 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, is_reserved: Union[bool, object] = values.unset - ) -> PhoneNumberInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the PhoneNumberInstance + Update the PhoneNumberInstance and return response metadata :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - :returns: The updated PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._update(is_reserved=is_reserved) + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "IsReserved": serialize.boolean_to_string(is_reserved), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated PhoneNumberInstance + """ + payload, _, _ = await self._update_async(is_reserved=is_reserved) return PhoneNumberInstance( self._version, payload, @@ -303,6 +512,27 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PhoneNumberInstance and return response metadata + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + is_reserved=is_reserved + ) + instance = PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -321,6 +551,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: :param payload: Payload response from the API """ + return PhoneNumberInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -352,20 +583,17 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/PhoneNumbers".format(**self._solution) - def create( + def _create( self, sid: Union[str, object] = values.unset, phone_number: Union[str, object] = values.unset, is_reserved: Union[bool, object] = values.unset, - ) -> PhoneNumberInstance: + ) -> tuple: """ - Create the PhoneNumberInstance + Internal helper for create operation - :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. - :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. - :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - - :returns: The created PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -377,28 +605,70 @@ def create( ) headers = values.of({"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, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Create the PhoneNumberInstance + + :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. + :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The created PhoneNumberInstance + """ + payload, _, _ = self._create( + sid=sid, phone_number=phone_number, is_reserved=is_reserved + ) return PhoneNumberInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, sid: Union[str, object] = values.unset, phone_number: Union[str, object] = values.unset, is_reserved: Union[bool, object] = values.unset, - ) -> PhoneNumberInstance: + ) -> ApiResponse: """ - Asynchronously create the PhoneNumberInstance + Create the PhoneNumberInstance and return response metadata :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - :returns: The created PhoneNumberInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + sid=sid, phone_number=phone_number, is_reserved=is_reserved + ) + instance = PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -410,14 +680,59 @@ async def create_async( ) headers = values.of({"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, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronously create the PhoneNumberInstance + + :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. + :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The created PhoneNumberInstance + """ + payload, _, _ = await self._create_async( + sid=sid, phone_number=phone_number, is_reserved=is_reserved + ) return PhoneNumberInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the PhoneNumberInstance and return response metadata + + :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. + :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + sid=sid, phone_number=phone_number, is_reserved=is_reserved + ) + instance = PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -468,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, @@ -487,6 +852,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -513,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( @@ -521,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, @@ -545,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, @@ -572,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: """ @@ -587,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: """ @@ -599,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 cfd547b1e7..ba7ee376b3 100644 --- a/twilio/rest/proxy/v1/service/session/__init__.py +++ b/twilio/rest/proxy/v1/service/session/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -99,6 +100,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[SessionContext] = None @property @@ -135,6 +137,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SessionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SessionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SessionInstance": """ Fetch the SessionInstance @@ -153,6 +173,24 @@ async def fetch_async(self) -> "SessionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SessionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SessionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, date_expiry: Union[datetime, object] = values.unset, @@ -195,6 +233,48 @@ async def update_async( status=status, ) + def update_with_http_info( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Update the SessionInstance with HTTP info + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) + + async def update_with_http_info_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SessionInstance with HTTP info + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) + @property def interactions(self) -> InteractionList: """ @@ -241,6 +321,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._interactions: Optional[InteractionList] = None self._participants: Optional[ParticipantList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SessionInstance @@ -248,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: @@ -260,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: @@ -272,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: """ @@ -292,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 + Internal helper for update operation - :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. - :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. - :param status: - - :returns: The updated SessionInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "DateExpiry": serialize.iso8601_datetime(date_expiry), @@ -327,13 +503,32 @@ 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, + 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, @@ -341,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), @@ -363,13 +582,34 @@ 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, + 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, @@ -377,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: """ @@ -421,6 +687,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SessionInstance: :param payload: Payload response from the API """ + return SessionInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -452,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, @@ -460,18 +727,12 @@ def create( mode: Union["SessionInstance.Mode", object] = values.unset, status: Union["SessionInstance.Status", object] = values.unset, participants: Union[List[object], object] = values.unset, - ) -> SessionInstance: + ) -> tuple: """ - Create the SessionInstance + 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( @@ -488,15 +749,48 @@ def create( ) headers = values.of({"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, + 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, @@ -504,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. @@ -515,7 +809,35 @@ async def create_async( :param status: :param participants: The Participant objects to include in the new session. - :returns: The created SessionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + date_expiry=date_expiry, + ttl=ttl, + mode=mode, + status=status, + participants=participants, + ) + instance = SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + mode: Union["SessionInstance.Mode", object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + participants: Union[List[object], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -532,14 +854,81 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -590,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, @@ -609,6 +1048,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -635,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( @@ -643,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, @@ -667,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, @@ -694,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: """ @@ -709,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: """ @@ -721,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 6e4cac7c14..abf834776c 100644 --- a/twilio/rest/proxy/v1/service/session/interaction.py +++ b/twilio/rest/proxy/v1/service/session/interaction.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -123,6 +124,7 @@ def __init__( "session_sid": session_sid, "sid": sid or self.sid, } + self._context: Optional[InteractionContext] = None @property @@ -160,6 +162,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the InteractionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InteractionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "InteractionInstance": """ Fetch the InteractionInstance @@ -178,6 +198,24 @@ async def fetch_async(self) -> "InteractionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -213,6 +251,20 @@ def __init__(self, version: Version, service_sid: str, session_sid: str, sid: st ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the InteractionInstance @@ -220,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: @@ -232,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: @@ -244,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: """ @@ -265,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: """ @@ -297,6 +435,7 @@ def get_instance(self, payload: Dict[str, Any]) -> InteractionInstance: :param payload: Payload response from the API """ + return InteractionInstance( self._version, payload, @@ -387,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, @@ -406,6 +595,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -432,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( @@ -440,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, @@ -464,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, @@ -491,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: """ @@ -506,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: """ @@ -518,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 e2eb3eaae8..90c3af7080 100644 --- a/twilio/rest/proxy/v1/service/session/participant/__init__.py +++ b/twilio/rest/proxy/v1/service/session/participant/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def __init__( "session_sid": session_sid, "sid": sid or self.sid, } + self._context: Optional[ParticipantContext] = None @property @@ -114,6 +116,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ParticipantInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ParticipantInstance": """ Fetch the ParticipantInstance @@ -132,6 +152,24 @@ async def fetch_async(self) -> "ParticipantInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def message_interactions(self) -> MessageInteractionList: """ @@ -176,6 +214,20 @@ def __init__(self, version: Version, service_sid: str, session_sid: str, sid: st self._message_interactions: Optional[MessageInteractionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ParticipantInstance @@ -183,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: @@ -195,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: @@ -207,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: """ @@ -228,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: @@ -274,6 +412,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: :param payload: Payload response from the API """ + return ParticipantInstance( self._version, payload, @@ -314,22 +453,18 @@ def __init__(self, version: Version, service_sid: str, session_sid: str): ) ) - def create( + def _create( self, identifier: str, friendly_name: Union[str, object] = values.unset, proxy_identifier: Union[str, object] = values.unset, proxy_identifier_sid: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> tuple: """ - Create the ParticipantInstance + Internal helper for create operation - :param identifier: The phone number of the Participant. - :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** - :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. - :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. - - :returns: The created ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -342,10 +477,37 @@ def create( ) headers = values.of({"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, + 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, @@ -353,22 +515,49 @@ def create( session_sid=self._solution["session_sid"], ) - async def create_async( + def create_with_http_info( self, identifier: str, friendly_name: Union[str, object] = values.unset, proxy_identifier: Union[str, object] = values.unset, proxy_identifier_sid: Union[str, object] = values.unset, - ) -> ParticipantInstance: + ) -> ApiResponse: """ - Asynchronously create the ParticipantInstance + Create the ParticipantInstance and return response metadata :param identifier: The phone number of the Participant. :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. - :returns: The created ParticipantInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identifier=identifier, + friendly_name=friendly_name, + proxy_identifier=proxy_identifier, + proxy_identifier_sid=proxy_identifier_sid, + ) + instance = ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identifier: str, + friendly_name: Union[str, object] = values.unset, + proxy_identifier: Union[str, object] = values.unset, + proxy_identifier_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -381,10 +570,37 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -392,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, @@ -442,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, @@ -461,6 +758,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -487,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( @@ -495,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, @@ -519,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, @@ -546,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: """ @@ -561,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: """ @@ -573,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 55ff64074e..49a2c998c4 100644 --- a/twilio/rest/proxy/v1/service/session/participant/message_interaction.py +++ b/twilio/rest/proxy/v1/service/session/participant/message_interaction.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -127,6 +128,7 @@ def __init__( "participant_sid": participant_sid, "sid": sid or self.sid, } + self._context: Optional[MessageInteractionContext] = None @property @@ -165,6 +167,24 @@ async def fetch_async(self) -> "MessageInteractionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessageInteractionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -207,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 @@ -214,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"], @@ -228,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: """ @@ -236,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"], @@ -250,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: """ @@ -269,6 +347,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessageInteractionInstance: :param payload: Payload response from the API """ + return MessageInteractionInstance( self._version, payload, @@ -312,18 +391,16 @@ def __init__( **self._solution ) - def create( + def _create( self, body: Union[str, object] = values.unset, media_url: Union[List[str], object] = values.unset, - ) -> MessageInteractionInstance: + ) -> tuple: """ - Create the MessageInteractionInstance - - :param body: The message to send to the participant - :param media_url: Reserved. Not currently supported. + Internal helper for create operation - :returns: The created MessageInteractionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -334,10 +411,28 @@ def create( ) headers = values.of({"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, + 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, @@ -346,18 +441,39 @@ def create( participant_sid=self._solution["participant_sid"], ) - async def create_async( + def create_with_http_info( self, body: Union[str, object] = values.unset, media_url: Union[List[str], object] = values.unset, - ) -> MessageInteractionInstance: + ) -> ApiResponse: """ - Asynchronously create the MessageInteractionInstance + Create the MessageInteractionInstance and return response metadata :param body: The message to send to the participant :param media_url: Reserved. Not currently supported. - :returns: The created MessageInteractionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(body=body, media_url=media_url) + instance = MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -368,10 +484,28 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -380,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, @@ -430,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, @@ -449,6 +658,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -475,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( @@ -483,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, @@ -507,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, @@ -534,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: """ @@ -549,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: """ @@ -561,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 e26514bff2..0000000000 --- a/twilio/rest/proxy/v1/service/short_code.py +++ /dev/null @@ -1,606 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Proxy - This is the public Twilio REST API. - - NOTE: This class is auto generated by OpenAPI Generator. - https://openapi-generator.tech - Do not edit the class manually. -""" - -from datetime import datetime -from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import deserialize, serialize, values -from twilio.base.instance_context import InstanceContext -from twilio.base.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version -from twilio.base.page import Page - - -class ShortCodeInstance(InstanceResource): - """ - :ivar sid: The unique string that we created to identify the ShortCode resource. - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource. - :ivar service_sid: The SID of the ShortCode resource's parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. - :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. - :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. - :ivar short_code: The short code's number. - :ivar iso_country: The ISO Country Code for the short code. - :ivar capabilities: - :ivar url: The absolute URL of the ShortCode resource. - :ivar is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - service_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.account_sid: Optional[str] = payload.get("account_sid") - self.service_sid: Optional[str] = payload.get("service_sid") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_updated") - ) - self.short_code: Optional[str] = payload.get("short_code") - self.iso_country: Optional[str] = payload.get("iso_country") - self.capabilities: Optional[str] = payload.get("capabilities") - self.url: Optional[str] = payload.get("url") - self.is_reserved: Optional[bool] = payload.get("is_reserved") - - self._solution = { - "service_sid": service_sid, - "sid": sid or self.sid, - } - self._context: Optional[ShortCodeContext] = None - - @property - def _proxy(self) -> "ShortCodeContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: ShortCodeContext for this ShortCodeInstance - """ - if self._context is None: - self._context = ShortCodeContext( - self._version, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the ShortCodeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ShortCodeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "ShortCodeInstance": - """ - Fetch the ShortCodeInstance - - - :returns: The fetched ShortCodeInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "ShortCodeInstance": - """ - Asynchronous coroutine to fetch the ShortCodeInstance - - - :returns: The fetched ShortCodeInstance - """ - return await self._proxy.fetch_async() - - def update( - self, is_reserved: Union[bool, object] = values.unset - ) -> "ShortCodeInstance": - """ - Update the ShortCodeInstance - - :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - - :returns: The updated ShortCodeInstance - """ - return self._proxy.update( - is_reserved=is_reserved, - ) - - async def update_async( - self, is_reserved: Union[bool, object] = values.unset - ) -> "ShortCodeInstance": - """ - Asynchronous coroutine to update the ShortCodeInstance - - :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. - - :returns: The updated ShortCodeInstance - """ - return await self._proxy.update_async( - is_reserved=is_reserved, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".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": serialize.boolean_to_string(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": serialize.boolean_to_string(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/en-us/messaging/channels/sms/short-codes) resource that represents the short code you would like to assign to your Proxy Service. - - :returns: The created ShortCodeInstance - """ - - data = values.of( - { - "Sid": sid, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ShortCodeInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - async def create_async(self, sid: str) -> ShortCodeInstance: - """ - Asynchronously create the ShortCodeInstance - - :param sid: The SID of a Twilio [ShortCode](https://www.twilio.com/en-us/messaging/channels/sms/short-codes) resource that represents the short code you would like to assign to your Proxy Service. - - :returns: The created ShortCodeInstance - """ - - data = values.of( - { - "Sid": sid, - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) - - return ShortCodeInstance( - self._version, payload, service_sid=self._solution["service_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[ShortCodeInstance]: - """ - Streams ShortCodeInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[ShortCodeInstance]: - """ - Asynchronously streams ShortCodeInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. - - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, stream() will attempt to read the - limit with the most efficient page size, i.e. min(limit, 1000) - - :returns: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async(page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[ShortCodeInstance]: - """ - Lists ShortCodeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return list( - self.stream( - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[ShortCodeInstance]: - """ - Asynchronously lists ShortCodeInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - but a limit is defined, list() will attempt to read the limit - with the most efficient page size, i.e. min(limit, 1000) - - :returns: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - page_token: Union[str, object] = values.unset, - page_number: Union[int, object] = values.unset, - page_size: Union[int, object] = values.unset, - ) -> ShortCodePage: - """ - Retrieve a single page of ShortCodeInstance records from the API. - Request is executed immediately - - :param page_token: PageToken provided by the API - :param page_number: Page Number, this value is simply for client state - :param page_size: Number of records to return, defaults to 50 - - :returns: Page of ShortCodeInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - 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/v2/phone_number.py b/twilio/rest/routes/v2/phone_number.py index 4f452e3616..56b49fed77 100644 --- a/twilio/rest/routes/v2/phone_number.py +++ b/twilio/rest/routes/v2/phone_number.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[PhoneNumberContext] = None @property @@ -92,6 +94,24 @@ async def fetch_async(self) -> "PhoneNumberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, voice_region: Union[str, object] = values.unset, @@ -128,6 +148,42 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the PhoneNumberInstance with HTTP info + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the PhoneNumberInstance with HTTP info + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + voice_region=voice_region, + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -155,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 @@ -162,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: """ @@ -181,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, @@ -206,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( @@ -236,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: """ diff --git a/twilio/rest/routes/v2/sip_domain.py b/twilio/rest/routes/v2/sip_domain.py index cad3a4922c..dd4445f3b6 100644 --- a/twilio/rest/routes/v2/sip_domain.py +++ b/twilio/rest/routes/v2/sip_domain.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( self._solution = { "sip_domain": sip_domain or self.sip_domain, } + self._context: Optional[SipDomainContext] = None @property @@ -92,6 +94,24 @@ async def fetch_async(self) -> "SipDomainInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SipDomainInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SipDomainInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, voice_region: Union[str, object] = values.unset, @@ -128,6 +148,42 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SipDomainInstance with HTTP info + + :param voice_region: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SipDomainInstance with HTTP info + + :param voice_region: + :param friendly_name: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + voice_region=voice_region, + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -155,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 @@ -162,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: """ @@ -181,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, @@ -206,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( @@ -236,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: """ diff --git a/twilio/rest/routes/v2/trunk.py b/twilio/rest/routes/v2/trunk.py index 2baf2788ae..72d14c90bc 100644 --- a/twilio/rest/routes/v2/trunk.py +++ b/twilio/rest/routes/v2/trunk.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( self._solution = { "sip_trunk_domain": sip_trunk_domain or self.sip_trunk_domain, } + self._context: Optional[TrunkContext] = None @property @@ -92,6 +94,24 @@ async def fetch_async(self) -> "TrunkInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, voice_region: Union[str, object] = values.unset, @@ -128,6 +148,42 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the TrunkInstance with HTTP info + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrunkInstance with HTTP info + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + voice_region=voice_region, + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -155,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 @@ -162,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: """ @@ -181,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, @@ -206,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( @@ -236,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: """ diff --git a/twilio/rest/serverless/v1/service/__init__.py b/twilio/rest/serverless/v1/service/__init__.py index 1658e671f4..2210d07e2e 100644 --- a/twilio/rest/serverless/v1/service/__init__.py +++ b/twilio/rest/serverless/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -65,6 +66,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -100,6 +102,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -118,6 +138,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, include_credentials: Union[bool, object] = values.unset, @@ -160,6 +198,48 @@ async def update_async( ui_editable=ui_editable, ) + def update_with_http_info( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + + async def update_with_http_info_async( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + @property def assets(self) -> AssetList: """ @@ -220,6 +300,20 @@ def __init__(self, version: Version, sid: str): self._environments: Optional[EnvironmentList] = None self._functions: Optional[FunctionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ServiceInstance @@ -227,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: @@ -239,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: @@ -251,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: """ @@ -270,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, @@ -297,6 +503,49 @@ 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": serialize.boolean_to_string(include_credentials), @@ -304,14 +553,15 @@ def update( "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, @@ -328,21 +578,35 @@ async def update_async( :returns: The updated ServiceInstance """ - data = values.of( - { - "IncludeCredentials": serialize.boolean_to_string(include_credentials), - "FriendlyName": friendly_name, - "UiEditable": serialize.boolean_to_string(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: @@ -410,6 +674,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -434,22 +699,18 @@ def __init__(self, version: Version): self._uri = "/Services" - def create( + def _create( self, unique_name: str, friendly_name: str, include_credentials: Union[bool, object] = values.unset, ui_editable: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Create the ServiceInstance - - :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`. + Internal helper for create operation - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -462,13 +723,15 @@ def create( ) headers = values.of({"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 ServiceInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: str, friendly_name: str, @@ -476,7 +739,7 @@ async def create_async( ui_editable: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Asynchronously create the ServiceInstance + Create the ServiceInstance :param unique_name: A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. @@ -485,6 +748,53 @@ async def create_async( :returns: The created ServiceInstance """ + payload, _, _ = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + include_credentials=include_credentials, + ui_editable=ui_editable, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param unique_name: A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param include_credentials: Whether to inject Account credentials into a function invocation context. The default value is `true`. + :param ui_editable: Whether the Service's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + include_credentials=include_credentials, + ui_editable=ui_editable, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -496,12 +806,65 @@ async def create_async( ) headers = values.of({"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, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param unique_name: A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param include_credentials: Whether to inject Account credentials into a function invocation context. The default value is `true`. + :param ui_editable: Whether the Service's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + include_credentials=include_credentials, + ui_editable=ui_editable, + ) return ServiceInstance(self._version, payload) + async def create_with_http_info_async( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :param unique_name: A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param include_credentials: Whether to inject Account credentials into a function invocation context. The default value is `true`. + :param ui_editable: Whether the Service's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, + friendly_name=friendly_name, + include_credentials=include_credentials, + ui_editable=ui_editable, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -552,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, @@ -571,6 +984,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -597,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( @@ -605,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, @@ -629,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( @@ -656,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 4e413db1da..8eae827c10 100644 --- a/twilio/rest/serverless/v1/service/asset/__init__.py +++ b/twilio/rest/serverless/v1/service/asset/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[AssetContext] = None @property @@ -97,6 +99,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssetInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssetInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AssetInstance": """ Fetch the AssetInstance @@ -115,6 +135,24 @@ async def fetch_async(self) -> "AssetInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, friendly_name: str) -> "AssetInstance": """ Update the AssetInstance @@ -139,6 +177,30 @@ async def update_async(self, friendly_name: str) -> "AssetInstance": friendly_name=friendly_name, ) + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the AssetInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the AssetInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + @property def asset_versions(self) -> AssetVersionList: """ @@ -177,6 +239,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._asset_versions: Optional[AssetVersionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the AssetInstance @@ -184,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: @@ -196,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: @@ -208,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: """ @@ -228,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, @@ -241,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({}) + + 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) -> 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, @@ -268,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, @@ -295,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: """ @@ -326,6 +546,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AssetInstance: :param payload: Payload response from the API """ + return AssetInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -357,13 +578,12 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Assets".format(**self._solution) - def create(self, friendly_name: str) -> AssetInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the AssetInstance + 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( @@ -373,21 +593,47 @@ def create(self, friendly_name: str) -> AssetInstance: ) headers = values.of({"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, 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( @@ -397,14 +643,43 @@ async def create_async(self, friendly_name: str) -> AssetInstance: ) headers = values.of({"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, 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, @@ -455,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, @@ -474,6 +799,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -500,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( @@ -508,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, @@ -532,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, @@ -559,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: """ @@ -574,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: """ @@ -586,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 fbe7b30800..a8d50afe6b 100644 --- a/twilio/rest/serverless/v1/service/asset/asset_version.py +++ b/twilio/rest/serverless/v1/service/asset/asset_version.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def __init__( "asset_sid": asset_sid, "sid": sid or self.sid, } + self._context: Optional[AssetVersionContext] = None @property @@ -105,6 +107,24 @@ async def fetch_async(self) -> "AssetVersionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssetVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssetVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -138,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 @@ -145,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: """ @@ -166,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: """ @@ -198,6 +274,7 @@ def get_instance(self, payload: Dict[str, Any]) -> AssetVersionInstance: :param payload: Payload response from the API """ + return AssetVersionInstance( self._version, payload, @@ -286,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, @@ -305,6 +432,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -331,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( @@ -339,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, @@ -363,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, @@ -390,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: """ @@ -405,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: """ @@ -417,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 90e5ccec41..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,8 +25,16 @@ from twilio.rest.serverless.v1.service.build.build_status import BuildStatusList + + + + + + class BuildInstance(InstanceResource): + + class Runtime(object): NODE8 = "node8" NODE10 = "node10" @@ -33,6 +42,8 @@ class Runtime(object): NODE14 = "node14" NODE16 = "node16" NODE18 = "node18" + NODE20 = "node20" + NODE22 = "node22" class Status(object): BUILDING = "building" @@ -54,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) @@ -72,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 @@ -107,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": @@ -126,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: @@ -145,6 +195,7 @@ def __repr__(self) -> str: class BuildContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the BuildContext @@ -166,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 @@ -173,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: """ @@ -182,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 @@ -192,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: """ @@ -210,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 @@ -260,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: """ @@ -295,16 +463,12 @@ def __init__(self, version: Version, service_sid: str): - def create(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> BuildInstance: + def _create(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> tuple: """ - Create the BuildInstance + Internal helper for create operation - :param asset_versions: The list of Asset Version resource SIDs to include in the Build. - :param function_versions: The list of the Function Version resource SIDs to include in the Build. - :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. - :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. - - :returns: The created BuildInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of({ @@ -317,21 +481,49 @@ def create(self, asset_versions: Union[List[str], object]=values.unset, function 'Content-Type': 'application/x-www-form-urlencoded' }) + headers["Content-Type"] = "application/x-www-form-urlencoded" + + + headers["Accept"] = "application/json" + - payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers) + return self._version.create_with_response_info(method='POST', uri=self._uri, data=data, headers=headers) + def create(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> BuildInstance: + """ + Create the BuildInstance + + :param asset_versions: The list of Asset Version resource SIDs to include in the Build. + :param function_versions: The list of the Function Version resource SIDs to include in the Build. + :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. + :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. + + :returns: The created BuildInstance + """ + payload, _, _ = self._create(asset_versions=asset_versions, function_versions=function_versions, dependencies=dependencies, runtime=runtime) return BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) - async def create_async(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> BuildInstance: + def create_with_http_info(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> ApiResponse: """ - Asynchronously create the BuildInstance + Create the BuildInstance and return response metadata :param asset_versions: The list of Asset Version resource SIDs to include in the Build. :param function_versions: The list of the Function Version resource SIDs to include in the Build. :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. - :returns: The created BuildInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(asset_versions=asset_versions, function_versions=function_versions, dependencies=dependencies, runtime=runtime) + instance = BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of({ @@ -344,10 +536,42 @@ async def create_async(self, asset_versions: Union[List[str], object]=values.uns '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=headers) + headers["Accept"] = "application/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: + """ + Asynchronously create the BuildInstance + + :param asset_versions: The list of Asset Version resource SIDs to include in the Build. + :param function_versions: The list of the Function Version resource SIDs to include in the Build. + :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. + :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. + + :returns: The created BuildInstance + """ + payload, _, _ = await self._create_async(asset_versions=asset_versions, function_versions=function_versions, dependencies=dependencies, runtime=runtime) return BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + + async def create_with_http_info_async(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> ApiResponse: + """ + Asynchronously create the BuildInstance and return response metadata + + :param asset_versions: The list of Asset Version resource SIDs to include in the Build. + :param function_versions: The list of the Function Version resource SIDs to include in the Build. + :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. + :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(asset_versions=asset_versions, function_versions=function_versions, dependencies=dependencies, runtime=runtime) + instance = BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream(self, @@ -404,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, @@ -420,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, @@ -444,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, @@ -474,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, @@ -499,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: """ @@ -515,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: """ @@ -530,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) @@ -560,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 2613ae3cb6..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: @@ -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 e9df6ecb2a..f5817a338c 100644 --- a/twilio/rest/serverless/v1/service/environment/__init__.py +++ b/twilio/rest/serverless/v1/service/environment/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -69,6 +70,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[EnvironmentContext] = None @property @@ -105,6 +107,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EnvironmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EnvironmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "EnvironmentInstance": """ Fetch the EnvironmentInstance @@ -123,6 +143,24 @@ async def fetch_async(self) -> "EnvironmentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EnvironmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EnvironmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def deployments(self) -> DeploymentList: """ @@ -179,6 +217,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._logs: Optional[LogList] = None self._variables: Optional[VariableList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the EnvironmentInstance @@ -186,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: @@ -198,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: @@ -210,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: """ @@ -230,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: @@ -300,6 +436,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EnvironmentInstance: :param payload: Payload response from the API """ + return EnvironmentInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -331,16 +468,14 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Environments".format(**self._solution) - def create( + def _create( self, unique_name: str, domain_suffix: Union[str, object] = values.unset - ) -> EnvironmentInstance: + ) -> tuple: """ - Create the EnvironmentInstance + Internal helper for create operation - :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. - :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. - - :returns: The created EnvironmentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -351,24 +486,59 @@ def create( ) headers = values.of({"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, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> EnvironmentInstance: + """ + Create the EnvironmentInstance + + :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. + :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. + + :returns: The created EnvironmentInstance + """ + payload, _, _ = self._create( + unique_name=unique_name, domain_suffix=domain_suffix + ) return EnvironmentInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, unique_name: str, domain_suffix: Union[str, object] = values.unset - ) -> EnvironmentInstance: + ) -> ApiResponse: """ - Asynchronously create the EnvironmentInstance + Create the EnvironmentInstance and return response metadata :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. - :returns: The created EnvironmentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, domain_suffix=domain_suffix + ) + instance = EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -379,14 +549,51 @@ async def create_async( ) headers = values.of({"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, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> EnvironmentInstance: + """ + Asynchronously create the EnvironmentInstance + + :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. + :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. + + :returns: The created EnvironmentInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, domain_suffix=domain_suffix + ) return EnvironmentInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the EnvironmentInstance and return response metadata + + :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. + :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, domain_suffix=domain_suffix + ) + instance = EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -437,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, @@ -456,6 +713,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -482,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( @@ -490,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, @@ -514,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, @@ -541,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: """ @@ -556,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: """ @@ -568,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 63ef1b4610..65fecb891a 100644 --- a/twilio/rest/serverless/v1/service/environment/deployment.py +++ b/twilio/rest/serverless/v1/service/environment/deployment.py @@ -14,7 +14,8 @@ 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 @@ -62,6 +63,7 @@ def __init__( "environment_sid": environment_sid, "sid": sid or self.sid, } + self._context: Optional[DeploymentContext] = None @property @@ -99,6 +101,24 @@ async def fetch_async(self) -> "DeploymentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeploymentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DeploymentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -134,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 @@ -141,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: """ @@ -162,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: """ @@ -194,6 +270,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DeploymentInstance: :param payload: Payload response from the API """ + return DeploymentInstance( self._version, payload, @@ -234,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( + 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, @@ -263,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"}) - 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, + 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, @@ -292,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, @@ -342,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, @@ -361,6 +578,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -387,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( @@ -395,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, @@ -419,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, @@ -446,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: """ @@ -461,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: """ @@ -473,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 e1aff5214f..30ff705ac5 100644 --- a/twilio/rest/serverless/v1/service/environment/log.py +++ b/twilio/rest/serverless/v1/service/environment/log.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,12 +24,6 @@ class LogInstance(InstanceResource): - - class Level(object): - INFO = "info" - WARN = "warn" - ERROR = "error" - """ :ivar sid: The unique string that we created to identify the Log resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Log resource. @@ -38,7 +33,7 @@ class Level(object): :ivar deployment_sid: The SID of the deployment that corresponds to the log. :ivar function_sid: The SID of the function whose invocation produced the log. :ivar request_sid: The SID of the request associated with the log. - :ivar level: + :ivar level: The log level. :ivar message: The log message. :ivar date_created: The date and time in GMT when the Log resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar url: The absolute URL of the Log resource. @@ -62,7 +57,7 @@ def __init__( self.deployment_sid: Optional[str] = payload.get("deployment_sid") self.function_sid: Optional[str] = payload.get("function_sid") self.request_sid: Optional[str] = payload.get("request_sid") - self.level: Optional["LogInstance.Level"] = payload.get("level") + self.level: Optional[str] = payload.get("level") self.message: Optional[str] = payload.get("message") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") @@ -74,6 +69,7 @@ def __init__( "environment_sid": environment_sid, "sid": sid or self.sid, } + self._context: Optional[LogContext] = None @property @@ -111,6 +107,24 @@ async def fetch_async(self) -> "LogInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the LogInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the LogInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -148,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 @@ -155,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: """ @@ -176,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: """ @@ -208,6 +278,7 @@ def get_instance(self, payload: Dict[str, Any]) -> LogInstance: :param payload: Payload response from the API """ + return LogInstance( self._version, payload, @@ -320,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, @@ -345,6 +486,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( function_sid=function_sid, @@ -380,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( @@ -391,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, @@ -424,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, @@ -460,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: """ @@ -475,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: """ @@ -487,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 99027536f3..13597a5419 100644 --- a/twilio/rest/serverless/v1/service/environment/variable.py +++ b/twilio/rest/serverless/v1/service/environment/variable.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -64,6 +65,7 @@ def __init__( "environment_sid": environment_sid, "sid": sid or self.sid, } + self._context: Optional[VariableContext] = None @property @@ -101,6 +103,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the VariableInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the VariableInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "VariableInstance": """ Fetch the VariableInstance @@ -119,6 +139,24 @@ async def fetch_async(self) -> "VariableInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VariableInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VariableInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, key: Union[str, object] = values.unset, @@ -155,6 +193,42 @@ async def update_async( value=value, ) + def update_with_http_info( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the VariableInstance with HTTP info + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + key=key, + value=value, + ) + + async def update_with_http_info_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the VariableInstance with HTTP info + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + key=key, + value=value, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -190,6 +264,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the VariableInstance @@ -197,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: @@ -209,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: @@ -221,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: """ @@ -242,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, @@ -290,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" - 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, + 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, @@ -324,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 @@ -342,6 +594,7 @@ def get_instance(self, payload: Dict[str, Any]) -> VariableInstance: :param payload: Payload response from the API """ + return VariableInstance( self._version, payload, @@ -382,14 +635,12 @@ def __init__(self, version: Version, service_sid: str, environment_sid: str): ) ) - def create(self, key: str, value: str) -> VariableInstance: + def _create(self, key: str, value: str) -> tuple: """ - Create the VariableInstance - - :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( @@ -400,10 +651,24 @@ def create(self, key: str, value: str) -> VariableInstance: ) headers = values.of({"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, 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, @@ -411,14 +676,30 @@ def create(self, key: str, value: str) -> VariableInstance: environment_sid=self._solution["environment_sid"], ) - async def create_async(self, key: str, value: str) -> VariableInstance: + def create_with_http_info(self, key: str, value: str) -> ApiResponse: """ - Asynchronously create the VariableInstance + Create the VariableInstance and return response metadata :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. - :returns: The created VariableInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(key=key, value=value) + instance = VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, key: str, value: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -429,10 +710,24 @@ async def create_async(self, key: str, value: str) -> VariableInstance: ) headers = values.of({"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, 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, @@ -440,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, @@ -490,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, @@ -509,6 +872,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -535,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( @@ -543,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, @@ -567,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, @@ -594,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: """ @@ -609,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: """ @@ -621,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 25a3ef935f..31c142d1f8 100644 --- a/twilio/rest/serverless/v1/service/function/__init__.py +++ b/twilio/rest/serverless/v1/service/function/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -63,6 +64,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[FunctionContext] = None @property @@ -99,6 +101,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FunctionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FunctionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "FunctionInstance": """ Fetch the FunctionInstance @@ -117,6 +137,24 @@ async def fetch_async(self) -> "FunctionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FunctionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FunctionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, friendly_name: str) -> "FunctionInstance": """ Update the FunctionInstance @@ -141,6 +179,30 @@ async def update_async(self, friendly_name: str) -> "FunctionInstance": friendly_name=friendly_name, ) + def update_with_http_info(self, friendly_name: str) -> ApiResponse: + """ + Update the FunctionInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async(self, friendly_name: str) -> ApiResponse: + """ + Asynchronous coroutine to update the FunctionInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + @property def function_versions(self) -> FunctionVersionList: """ @@ -179,6 +241,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._function_versions: Optional[FunctionVersionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the FunctionInstance @@ -186,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: @@ -198,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: @@ -210,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: """ @@ -230,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, @@ -243,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({}) + + 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) -> 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, @@ -270,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, @@ -297,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: """ @@ -328,6 +548,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FunctionInstance: :param payload: Payload response from the API """ + return FunctionInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -359,13 +580,12 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Functions".format(**self._solution) - def create(self, friendly_name: str) -> FunctionInstance: + def _create(self, friendly_name: str) -> tuple: """ - Create the FunctionInstance + 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( @@ -375,21 +595,47 @@ def create(self, friendly_name: str) -> FunctionInstance: ) headers = values.of({"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, 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( @@ -399,14 +645,43 @@ async def create_async(self, friendly_name: str) -> FunctionInstance: ) headers = values.of({"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, 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, @@ -457,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, @@ -476,6 +801,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -502,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( @@ -510,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, @@ -534,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, @@ -561,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: """ @@ -576,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: """ @@ -588,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 e915894f11..75cdb11b4f 100644 --- a/twilio/rest/serverless/v1/service/function/function_version/__init__.py +++ b/twilio/rest/serverless/v1/service/function/function_version/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -73,6 +74,7 @@ def __init__( "function_sid": function_sid, "sid": sid or self.sid, } + self._context: Optional[FunctionVersionContext] = None @property @@ -110,6 +112,24 @@ async def fetch_async(self) -> "FunctionVersionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FunctionVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FunctionVersionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def function_version_content(self) -> FunctionVersionContentList: """ @@ -154,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 @@ -161,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: """ @@ -182,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: @@ -228,6 +304,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FunctionVersionInstance: :param payload: Payload response from the API """ + return FunctionVersionInstance( self._version, payload, @@ -316,6 +393,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams 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, @@ -335,6 +462,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -361,6 +489,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -369,6 +498,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists 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, @@ -393,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, @@ -420,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: """ @@ -435,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: """ @@ -447,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 c58fa574e7..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 @@ -13,6 +13,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 @@ -51,6 +53,7 @@ def __init__( "function_sid": function_sid, "sid": sid, } + self._context: Optional[FunctionVersionContentContext] = None @property @@ -88,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 @@ -123,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 @@ -130,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: """ @@ -151,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: """ diff --git a/twilio/rest/studio/v1/flow/__init__.py b/twilio/rest/studio/v1/flow/__init__.py index bb0f78658b..a2795280f7 100644 --- a/twilio/rest/studio/v1/flow/__init__.py +++ b/twilio/rest/studio/v1/flow/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -64,6 +65,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[FlowContext] = None @property @@ -99,6 +101,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FlowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "FlowInstance": """ Fetch the FlowInstance @@ -117,6 +137,24 @@ async def fetch_async(self) -> "FlowInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def engagements(self) -> EngagementList: """ @@ -161,6 +199,20 @@ def __init__(self, version: Version, sid: str): self._engagements: Optional[EngagementList] = None self._executions: Optional[ExecutionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the FlowInstance @@ -168,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: @@ -180,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: @@ -192,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: """ @@ -211,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: @@ -265,6 +399,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FlowInstance: :param payload: Payload response from the API """ + return FlowInstance(self._version, payload) def __repr__(self) -> str: @@ -339,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, @@ -358,6 +543,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -384,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( @@ -392,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, @@ -416,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( @@ -443,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 db0c846e5c..a899206caf 100644 --- a/twilio/rest/studio/v1/flow/engagement/__init__.py +++ b/twilio/rest/studio/v1/flow/engagement/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def __init__( "flow_sid": flow_sid, "sid": sid or self.sid, } + self._context: Optional[EngagementContext] = None @property @@ -113,6 +115,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EngagementInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EngagementInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "EngagementInstance": """ Fetch the EngagementInstance @@ -131,6 +151,24 @@ async def fetch_async(self) -> "EngagementInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EngagementInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EngagementInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def engagement_context(self) -> EngagementContextList: """ @@ -177,6 +215,20 @@ def __init__(self, version: Version, flow_sid: str, sid: str): self._engagement_context: Optional[EngagementContextList] = None self._steps: Optional[StepList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the EngagementInstance @@ -184,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: @@ -196,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: @@ -208,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: """ @@ -228,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: @@ -285,6 +421,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EngagementInstance: :param payload: Payload response from the API """ + return EngagementInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) @@ -316,17 +453,14 @@ def __init__(self, version: Version, flow_sid: str): } self._uri = "/Flows/{flow_sid}/Engagements".format(**self._solution) - def create( + def _create( self, to: str, from_: str, parameters: Union[object, object] = values.unset - ) -> EngagementInstance: + ) -> tuple: """ - Create the EngagementInstance + Internal helper for create operation - :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. - :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` - :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. - - :returns: The created EngagementInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -338,25 +472,59 @@ def create( ) headers = values.of({"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, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> EngagementInstance: + """ + Create the EngagementInstance + + :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` + :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. + + :returns: The created EngagementInstance + """ + payload, _, _ = self._create(to=to, from_=from_, parameters=parameters) return EngagementInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) - async def create_async( + def create_with_http_info( self, to: str, from_: str, parameters: Union[object, object] = values.unset - ) -> EngagementInstance: + ) -> ApiResponse: """ - Asynchronously create the EngagementInstance + Create the EngagementInstance and return response metadata :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. - :returns: The created EngagementInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, from_=from_, parameters=parameters + ) + instance = EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -368,14 +536,53 @@ async def create_async( ) headers = values.of({"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, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> EngagementInstance: + """ + Asynchronously create the EngagementInstance + + :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` + :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. + + :returns: The created EngagementInstance + """ + payload, _, _ = await self._create_async( + to=to, from_=from_, parameters=parameters + ) return EngagementInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) + async def create_with_http_info_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the EngagementInstance and return response metadata + + :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` + :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, from_=from_, parameters=parameters + ) + instance = EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -426,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, @@ -445,6 +702,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -471,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( @@ -479,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, @@ -503,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, @@ -530,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: """ @@ -545,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: """ @@ -557,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 f534db6922..3b0cf3cf52 100644 --- a/twilio/rest/studio/v1/flow/engagement/engagement_context.py +++ b/twilio/rest/studio/v1/flow/engagement/engagement_context.py @@ -13,6 +13,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 @@ -47,6 +49,7 @@ def __init__( "flow_sid": flow_sid, "engagement_sid": engagement_sid, } + self._context: Optional[EngagementContextContext] = None @property @@ -83,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 @@ -114,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 @@ -121,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: """ @@ -141,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: """ diff --git a/twilio/rest/studio/v1/flow/engagement/step/__init__.py b/twilio/rest/studio/v1/flow/engagement/step/__init__.py index 1a2d8570c9..25a925f124 100644 --- a/twilio/rest/studio/v1/flow/engagement/step/__init__.py +++ b/twilio/rest/studio/v1/flow/engagement/step/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,8 +32,10 @@ class StepInstance(InstanceResource): :ivar engagement_sid: The SID of the Engagement. :ivar name: The event that caused the Flow to transition to the Step. :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar parent_step_sid: The SID of the parent Step. :ivar transitioned_from: The Widget that preceded the Widget for the Step. :ivar transitioned_to: The Widget that will follow the Widget for the Step. + :ivar type: The type of the widget that was executed. :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar url: The absolute URL of the resource. @@ -55,8 +58,10 @@ def __init__( self.engagement_sid: Optional[str] = payload.get("engagement_sid") self.name: Optional[str] = payload.get("name") self.context: Optional[Dict[str, object]] = payload.get("context") + self.parent_step_sid: Optional[str] = payload.get("parent_step_sid") self.transitioned_from: Optional[str] = payload.get("transitioned_from") self.transitioned_to: Optional[str] = payload.get("transitioned_to") + self.type: Optional[str] = payload.get("type") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -71,6 +76,7 @@ def __init__( "engagement_sid": engagement_sid, "sid": sid or self.sid, } + self._context: Optional[StepContext] = None @property @@ -108,6 +114,24 @@ async def fetch_async(self) -> "StepInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the StepInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the StepInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def step_context(self) -> StepContextList: """ @@ -150,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 @@ -157,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: """ @@ -178,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: @@ -224,6 +304,7 @@ def get_instance(self, payload: Dict[str, Any]) -> StepInstance: :param payload: Payload response from the API """ + return StepInstance( self._version, payload, @@ -312,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, @@ -331,6 +462,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -357,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( @@ -365,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, @@ -389,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, @@ -416,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: """ @@ -431,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: """ @@ -443,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 69c4c22465..26f82d470d 100644 --- a/twilio/rest/studio/v1/flow/engagement/step/step_context.py +++ b/twilio/rest/studio/v1/flow/engagement/step/step_context.py @@ -13,6 +13,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 @@ -51,6 +53,7 @@ def __init__( "engagement_sid": engagement_sid, "step_sid": step_sid, } + self._context: Optional[StepContextContext] = None @property @@ -88,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 @@ -123,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 @@ -130,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: """ @@ -151,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: """ diff --git a/twilio/rest/studio/v1/flow/execution/__init__.py b/twilio/rest/studio/v1/flow/execution/__init__.py index 6a32cb3020..5ee77d109e 100644 --- a/twilio/rest/studio/v1/flow/execution/__init__.py +++ b/twilio/rest/studio/v1/flow/execution/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,6 +76,7 @@ def __init__( "flow_sid": flow_sid, "sid": sid or self.sid, } + self._context: Optional[ExecutionContext] = None @property @@ -111,6 +113,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ExecutionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ExecutionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ExecutionInstance": """ Fetch the ExecutionInstance @@ -129,6 +149,24 @@ async def fetch_async(self) -> "ExecutionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, status: "ExecutionInstance.Status") -> "ExecutionInstance": """ Update the ExecutionInstance @@ -155,6 +193,32 @@ async def update_async( status=status, ) + def update_with_http_info(self, status: "ExecutionInstance.Status") -> ApiResponse: + """ + Update the ExecutionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "ExecutionInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ExecutionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + @property def execution_context(self) -> ExecutionContextList: """ @@ -201,6 +265,20 @@ def __init__(self, version: Version, flow_sid: str, sid: str): self._execution_context: Optional[ExecutionContextList] = None self._steps: Optional[ExecutionStepList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ExecutionInstance @@ -208,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: @@ -220,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: @@ -232,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: """ @@ -252,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, @@ -265,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, @@ -292,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({}) + + 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, @@ -321,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: """ @@ -365,6 +587,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ExecutionInstance: :param payload: Payload response from the API """ + return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) @@ -396,17 +619,14 @@ def __init__(self, version: Version, flow_sid: str): } self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) - def create( + def _create( self, to: str, from_: str, parameters: Union[object, object] = values.unset - ) -> ExecutionInstance: + ) -> tuple: """ - Create the ExecutionInstance - - :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. - :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. - :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + Internal helper for create operation - :returns: The created ExecutionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -418,25 +638,59 @@ def create( ) headers = values.of({"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, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + payload, _, _ = self._create(to=to, from_=from_, parameters=parameters) return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) - async def create_async( + def create_with_http_info( self, to: str, from_: str, parameters: Union[object, object] = values.unset - ) -> ExecutionInstance: + ) -> ApiResponse: """ - Asynchronously create the ExecutionInstance + Create the ExecutionInstance and return response metadata :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. - :returns: The created ExecutionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, from_=from_, parameters=parameters + ) + instance = ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -448,14 +702,53 @@ async def create_async( ) headers = values.of({"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, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Asynchronously create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + payload, _, _ = await self._create_async( + to=to, from_=from_, parameters=parameters + ) return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) + async def create_with_http_info_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the ExecutionInstance and return response metadata + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, from_=from_, parameters=parameters + ) + instance = ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, date_created_from: Union[datetime, object] = values.unset, @@ -522,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, @@ -545,6 +902,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created_from=date_created_from, @@ -577,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( @@ -587,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, @@ -617,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, @@ -650,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: """ @@ -665,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: """ @@ -677,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 a2765bbc9b..d12c6b3f93 100644 --- a/twilio/rest/studio/v1/flow/execution/execution_context.py +++ b/twilio/rest/studio/v1/flow/execution/execution_context.py @@ -13,6 +13,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 @@ -47,6 +49,7 @@ def __init__( "flow_sid": flow_sid, "execution_sid": execution_sid, } + self._context: Optional[ExecutionContextContext] = None @property @@ -83,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 @@ -114,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 @@ -121,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: """ @@ -141,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: """ 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 6e19ca4453..d09adb9984 100644 --- a/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py +++ b/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,10 +32,12 @@ class ExecutionStepInstance(InstanceResource): :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStep resource. :ivar flow_sid: The SID of the Flow. :ivar execution_sid: The SID of the Step's Execution resource. + :ivar parent_step_sid: This field shows the Step SID of the Widget in the parent Flow that started the Subflow. If this Step is not part of a Subflow execution, the value is null. :ivar name: The event that caused the Flow to transition to the Step. :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. :ivar transitioned_from: The Widget that preceded the Widget for the Step. :ivar transitioned_to: The Widget that will follow the Widget for the Step. + :ivar type: The type of the widget that was executed. :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar url: The absolute URL of the resource. @@ -55,10 +58,12 @@ def __init__( self.account_sid: Optional[str] = payload.get("account_sid") self.flow_sid: Optional[str] = payload.get("flow_sid") self.execution_sid: Optional[str] = payload.get("execution_sid") + self.parent_step_sid: Optional[str] = payload.get("parent_step_sid") self.name: Optional[str] = payload.get("name") self.context: Optional[Dict[str, object]] = payload.get("context") self.transitioned_from: Optional[str] = payload.get("transitioned_from") self.transitioned_to: Optional[str] = payload.get("transitioned_to") + self.type: Optional[str] = payload.get("type") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -73,6 +78,7 @@ def __init__( "execution_sid": execution_sid, "sid": sid or self.sid, } + self._context: Optional[ExecutionStepContext] = None @property @@ -110,6 +116,24 @@ async def fetch_async(self) -> "ExecutionStepInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionStepInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def step_context(self) -> ExecutionStepContextList: """ @@ -152,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 @@ -159,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: """ @@ -180,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: @@ -226,6 +306,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: :param payload: Payload response from the API """ + return ExecutionStepInstance( self._version, payload, @@ -314,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, @@ -333,6 +464,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -359,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( @@ -367,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, @@ -391,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, @@ -418,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: """ @@ -433,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: """ @@ -445,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 224f92d0f5..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 @@ -13,6 +13,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 @@ -51,6 +53,7 @@ def __init__( "execution_sid": execution_sid, "step_sid": step_sid, } + self._context: Optional[ExecutionStepContextContext] = None @property @@ -88,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 @@ -123,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 @@ -130,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: """ @@ -151,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: """ diff --git a/twilio/rest/studio/v2/flow/__init__.py b/twilio/rest/studio/v2/flow/__init__.py index 057c949696..c13e10be4c 100644 --- a/twilio/rest/studio/v2/flow/__init__.py +++ b/twilio/rest/studio/v2/flow/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -34,6 +35,7 @@ class Status(object): """ :ivar sid: The unique string that we created to identify the Flow resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flow resource. + :ivar author_sid: The SID of the User that created or last updated the Flow. :ivar friendly_name: The string that you assigned to describe the Flow. :ivar definition: JSON representation of flow definition. :ivar status: @@ -56,6 +58,7 @@ def __init__( self.sid: Optional[str] = payload.get("sid") self.account_sid: Optional[str] = payload.get("account_sid") + self.author_sid: Optional[str] = payload.get("author_sid") self.friendly_name: Optional[str] = payload.get("friendly_name") self.definition: Optional[Dict[str, object]] = payload.get("definition") self.status: Optional["FlowInstance.Status"] = payload.get("status") @@ -77,6 +80,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[FlowContext] = None @property @@ -112,6 +116,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FlowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "FlowInstance": """ Fetch the FlowInstance @@ -130,12 +152,31 @@ async def fetch_async(self) -> "FlowInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: "FlowInstance.Status", friendly_name: Union[str, object] = values.unset, definition: Union[object, object] = values.unset, commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, ) -> "FlowInstance": """ Update the FlowInstance @@ -144,6 +185,7 @@ def update( :param friendly_name: The string that you assigned to describe the Flow. :param definition: JSON representation of flow definition. :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. :returns: The updated FlowInstance """ @@ -152,6 +194,7 @@ def update( friendly_name=friendly_name, definition=definition, commit_message=commit_message, + author_sid=author_sid, ) async def update_async( @@ -160,6 +203,7 @@ async def update_async( friendly_name: Union[str, object] = values.unset, definition: Union[object, object] = values.unset, commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, ) -> "FlowInstance": """ Asynchronous coroutine to update the FlowInstance @@ -168,6 +212,7 @@ async def update_async( :param friendly_name: The string that you assigned to describe the Flow. :param definition: JSON representation of flow definition. :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. :returns: The updated FlowInstance """ @@ -176,6 +221,61 @@ async def update_async( friendly_name=friendly_name, definition=definition, commit_message=commit_message, + author_sid=author_sid, + ) + + def update_with_http_info( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the FlowInstance with HTTP info + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + + async def update_with_http_info_async( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FlowInstance with HTTP info + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created or last updated the Flow. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, ) @property @@ -230,6 +330,20 @@ def __init__(self, version: Version, sid: str): self._revisions: Optional[FlowRevisionList] = None self._test_users: Optional[FlowTestUserList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the FlowInstance @@ -237,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: @@ -249,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: @@ -261,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: """ @@ -280,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, @@ -298,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 @@ -306,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, @@ -332,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 @@ -340,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: @@ -414,6 +724,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FlowInstance: :param payload: Payload response from the API """ + return FlowInstance(self._version, payload) def __repr__(self) -> str: @@ -438,22 +749,19 @@ def __init__(self, version: Version): self._uri = "/Flows" - def create( + def _create( self, friendly_name: str, status: "FlowInstance.Status", definition: object, commit_message: Union[str, object] = values.unset, - ) -> FlowInstance: + author_sid: Union[str, object] = values.unset, + ) -> tuple: """ - Create the FlowInstance + Internal helper for create operation - :param friendly_name: The string that you assigned to describe the Flow. - :param status: - :param definition: JSON representation of flow definition. - :param commit_message: Description of change made in the revision. - - :returns: The created FlowInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -462,33 +770,90 @@ def create( "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( + 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 FlowInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, status: "FlowInstance.Status", definition: object, commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, ) -> FlowInstance: """ - Asynchronously create the FlowInstance + Create the FlowInstance :param friendly_name: The string that you assigned to describe the Flow. :param status: :param definition: JSON representation of flow definition. :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created the Flow. :returns: The created FlowInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + return FlowInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the FlowInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created the Flow. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + instance = FlowInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -496,16 +861,76 @@ async def create_async( "Status": status, "Definition": serialize.object(definition), "CommitMessage": commit_message, + "AuthorSid": author_sid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> FlowInstance: + """ + Asynchronously create the FlowInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created the Flow. + + :returns: The created FlowInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) return FlowInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the FlowInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + :param author_sid: The SID of the User that created the Flow. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + author_sid=author_sid, + ) + instance = FlowInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -556,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, @@ -575,6 +1050,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -601,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( @@ -609,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, @@ -633,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( @@ -660,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 18dcbf0629..0a0bfa6fed 100644 --- a/twilio/rest/studio/v2/flow/execution/__init__.py +++ b/twilio/rest/studio/v2/flow/execution/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -35,10 +36,13 @@ class Status(object): :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Execution resource. :ivar flow_sid: The SID of the Flow. :ivar contact_channel_address: The phone number, SIP address or Client identifier that triggered the Execution. Phone numbers are in E.164 format (e.g. +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. + :ivar contact_sid: The SID of the Contact. + :ivar flow_version: The Flow version number at the time of Execution creation. :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. :ivar status: :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar initiated_by: The SID or identifier that triggered this Execution. For example, a Call SID if triggered by an incoming call, a Message SID if triggered by an incoming message, a Request SID if triggered by a REST API request, and so on. :ivar url: The absolute URL of the resource. :ivar links: The URLs of nested resources. """ @@ -58,6 +62,10 @@ def __init__( self.contact_channel_address: Optional[str] = payload.get( "contact_channel_address" ) + self.contact_sid: Optional[str] = payload.get("contact_sid") + self.flow_version: Optional[int] = deserialize.integer( + payload.get("flow_version") + ) self.context: Optional[Dict[str, object]] = payload.get("context") self.status: Optional["ExecutionInstance.Status"] = payload.get("status") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( @@ -66,6 +74,7 @@ def __init__( self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_updated") ) + self.initiated_by: Optional[str] = payload.get("initiated_by") self.url: Optional[str] = payload.get("url") self.links: Optional[Dict[str, object]] = payload.get("links") @@ -73,6 +82,7 @@ def __init__( "flow_sid": flow_sid, "sid": sid or self.sid, } + self._context: Optional[ExecutionContext] = None @property @@ -109,6 +119,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ExecutionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ExecutionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ExecutionInstance": """ Fetch the ExecutionInstance @@ -127,6 +155,24 @@ async def fetch_async(self) -> "ExecutionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, status: "ExecutionInstance.Status") -> "ExecutionInstance": """ Update the ExecutionInstance @@ -153,6 +199,32 @@ async def update_async( status=status, ) + def update_with_http_info(self, status: "ExecutionInstance.Status") -> ApiResponse: + """ + Update the ExecutionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "ExecutionInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ExecutionInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + @property def execution_context(self) -> ExecutionContextList: """ @@ -199,6 +271,20 @@ def __init__(self, version: Version, flow_sid: str, sid: str): self._execution_context: Optional[ExecutionContextList] = None self._steps: Optional[ExecutionStepList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ExecutionInstance @@ -206,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: @@ -218,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: @@ -230,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: """ @@ -250,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, @@ -263,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, @@ -290,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" - 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: "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, @@ -319,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: """ @@ -363,6 +593,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ExecutionInstance: :param payload: Payload response from the API """ + return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) @@ -394,17 +625,14 @@ def __init__(self, version: Version, flow_sid: str): } self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) - def create( + def _create( self, to: str, from_: str, parameters: Union[object, object] = values.unset - ) -> ExecutionInstance: + ) -> tuple: """ - Create the ExecutionInstance - - :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. - :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. - :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + Internal helper for create operation - :returns: The created ExecutionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -416,25 +644,59 @@ def create( ) headers = values.of({"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, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + payload, _, _ = self._create(to=to, from_=from_, parameters=parameters) return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) - async def create_async( + def create_with_http_info( self, to: str, from_: str, parameters: Union[object, object] = values.unset - ) -> ExecutionInstance: + ) -> ApiResponse: """ - Asynchronously create the ExecutionInstance + Create the ExecutionInstance and return response metadata :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. - :returns: The created ExecutionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, from_=from_, parameters=parameters + ) + instance = ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -446,16 +708,56 @@ async def create_async( ) headers = values.of({"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, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Asynchronously create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + payload, _, _ = await self._create_async( + to=to, from_=from_, parameters=parameters + ) return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) + async def create_with_http_info_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the ExecutionInstance and return response metadata + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + to=to, from_=from_, parameters=parameters + ) + instance = ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, + status: Union["ExecutionInstance.Status", object] = values.unset, date_created_from: Union[datetime, object] = values.unset, date_created_to: Union[datetime, object] = values.unset, limit: Optional[int] = None, @@ -467,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() @@ -480,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"], @@ -489,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, @@ -500,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() @@ -513,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"], @@ -520,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, @@ -532,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 @@ -543,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, @@ -554,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, @@ -564,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 @@ -575,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, @@ -585,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, @@ -597,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 @@ -607,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, @@ -615,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, @@ -630,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 @@ -640,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, @@ -648,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: """ @@ -663,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: """ @@ -675,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 facb52eed7..d27773667f 100644 --- a/twilio/rest/studio/v2/flow/execution/execution_context.py +++ b/twilio/rest/studio/v2/flow/execution/execution_context.py @@ -13,6 +13,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 @@ -47,6 +49,7 @@ def __init__( "flow_sid": flow_sid, "execution_sid": execution_sid, } + self._context: Optional[ExecutionContextContext] = None @property @@ -83,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 @@ -114,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 @@ -121,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: """ @@ -141,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: """ 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 257e16b1df..57c14a8ab6 100644 --- a/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py +++ b/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,10 +32,12 @@ class ExecutionStepInstance(InstanceResource): :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStep resource. :ivar flow_sid: The SID of the Flow. :ivar execution_sid: The SID of the Step's Execution resource. + :ivar parent_step_sid: The SID of the parent Step. :ivar name: The event that caused the Flow to transition to the Step. :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. :ivar transitioned_from: The Widget that preceded the Widget for the Step. :ivar transitioned_to: The Widget that will follow the Widget for the Step. + :ivar type: The type of the widget that was executed. :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar url: The absolute URL of the resource. @@ -55,10 +58,12 @@ def __init__( self.account_sid: Optional[str] = payload.get("account_sid") self.flow_sid: Optional[str] = payload.get("flow_sid") self.execution_sid: Optional[str] = payload.get("execution_sid") + self.parent_step_sid: Optional[str] = payload.get("parent_step_sid") self.name: Optional[str] = payload.get("name") self.context: Optional[Dict[str, object]] = payload.get("context") self.transitioned_from: Optional[str] = payload.get("transitioned_from") self.transitioned_to: Optional[str] = payload.get("transitioned_to") + self.type: Optional[str] = payload.get("type") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -73,6 +78,7 @@ def __init__( "execution_sid": execution_sid, "sid": sid or self.sid, } + self._context: Optional[ExecutionStepContext] = None @property @@ -110,6 +116,24 @@ async def fetch_async(self) -> "ExecutionStepInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionStepInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def step_context(self) -> ExecutionStepContextList: """ @@ -152,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 @@ -159,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: """ @@ -180,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: @@ -226,6 +306,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: :param payload: Payload response from the API """ + return ExecutionStepInstance( self._version, payload, @@ -314,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, @@ -333,6 +464,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -359,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( @@ -367,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, @@ -391,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, @@ -418,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: """ @@ -433,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: """ @@ -445,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 41661238b5..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 @@ -13,6 +13,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 @@ -51,6 +53,7 @@ def __init__( "execution_sid": execution_sid, "step_sid": step_sid, } + self._context: Optional[ExecutionStepContextContext] = None @property @@ -88,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 @@ -123,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 @@ -130,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: """ @@ -151,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: """ diff --git a/twilio/rest/studio/v2/flow/flow_revision.py b/twilio/rest/studio/v2/flow/flow_revision.py index 0de91513ed..046e08d7c6 100644 --- a/twilio/rest/studio/v2/flow/flow_revision.py +++ b/twilio/rest/studio/v2/flow/flow_revision.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,6 +32,7 @@ class Status(object): """ :ivar sid: The unique string that we created to identify the Flow resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flow resource. + :ivar author_sid: The SID of the User that created or last updated the Flow. :ivar friendly_name: The string that you assigned to describe the Flow. :ivar definition: JSON representation of flow definition. :ivar status: @@ -54,6 +56,7 @@ def __init__( self.sid: Optional[str] = payload.get("sid") self.account_sid: Optional[str] = payload.get("account_sid") + self.author_sid: Optional[str] = payload.get("author_sid") self.friendly_name: Optional[str] = payload.get("friendly_name") self.definition: Optional[Dict[str, object]] = payload.get("definition") self.status: Optional["FlowRevisionInstance.Status"] = payload.get("status") @@ -73,6 +76,7 @@ def __init__( "sid": sid, "revision": revision or self.revision, } + self._context: Optional[FlowRevisionContext] = None @property @@ -109,6 +113,24 @@ async def fetch_async(self) -> "FlowRevisionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowRevisionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowRevisionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -138,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 @@ -145,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: """ @@ -165,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: """ @@ -196,6 +272,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FlowRevisionInstance: :param payload: Payload response from the API """ + return FlowRevisionInstance(self._version, payload, sid=self._solution["sid"]) def __repr__(self) -> str: @@ -275,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, @@ -294,6 +421,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -320,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( @@ -328,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, @@ -352,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, @@ -379,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: """ @@ -394,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: """ @@ -406,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 3465632353..c030529dde 100644 --- a/twilio/rest/studio/v2/flow/flow_test_user.py +++ b/twilio/rest/studio/v2/flow/flow_test_user.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -37,6 +38,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], sid: str): self._solution = { "sid": sid, } + self._context: Optional[FlowTestUserContext] = None @property @@ -72,6 +74,24 @@ async def fetch_async(self) -> "FlowTestUserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowTestUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FlowTestUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, test_users: List[str]) -> "FlowTestUserInstance": """ Update the FlowTestUserInstance @@ -96,6 +116,30 @@ async def update_async(self, test_users: List[str]) -> "FlowTestUserInstance": test_users=test_users, ) + def update_with_http_info(self, test_users: List[str]) -> ApiResponse: + """ + Update the FlowTestUserInstance with HTTP info + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + test_users=test_users, + ) + + async def update_with_http_info_async(self, test_users: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the FlowTestUserInstance with HTTP info + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + test_users=test_users, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -123,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 @@ -130,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: """ @@ -149,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" - 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, test_users: List[str]) -> FlowTestUserInstance: + """ + Asynchronous coroutine to update the FlowTestUserInstance + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: The updated FlowTestUserInstance + """ + payload, _, _ = await self._update_async(test_users=test_users) return FlowTestUserInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async(self, test_users: List[str]) -> ApiResponse: + """ + Asynchronous coroutine to update the FlowTestUserInstance and return response metadata + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async(test_users=test_users) + instance = FlowTestUserInstance( + self._version, payload, sid=self._solution["sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/studio/v2/flow_validate.py b/twilio/rest/studio/v2/flow_validate.py index 34f37e152f..390ad74ca3 100644 --- a/twilio/rest/studio/v2/flow_validate.py +++ b/twilio/rest/studio/v2/flow_validate.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,22 +59,18 @@ def __init__(self, version: Version): self._uri = "/Flows/Validate" - def update( + def _update( self, friendly_name: str, status: "FlowValidateInstance.Status", definition: object, commit_message: Union[str, object] = values.unset, - ) -> FlowValidateInstance: + ) -> tuple: """ - Update the FlowValidateInstance - - :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( @@ -86,28 +83,77 @@ def update( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, + 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( @@ -120,12 +166,65 @@ async def update_async( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowValidateInstance: + """ + Asynchronously update the FlowValidateInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The updated FlowValidateInstance + """ + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + ) return FlowValidateInstance(self._version, payload) + async def update_with_http_info_async( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously update the FlowValidateInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + status=status, + definition=definition, + commit_message=commit_message, + ) + instance = FlowValidateInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/supersim/v1/esim_profile.py b/twilio/rest/supersim/v1/esim_profile.py index 7e176bba7f..f60d8f11d0 100644 --- a/twilio/rest/supersim/v1/esim_profile.py +++ b/twilio/rest/supersim/v1/esim_profile.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EsimProfileContext] = None @property @@ -111,6 +113,24 @@ async def fetch_async(self) -> "EsimProfileInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EsimProfileInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EsimProfileInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -138,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 @@ -145,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: """ @@ -164,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: """ @@ -194,6 +266,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EsimProfileInstance: :param payload: Payload response from the API """ + return EsimProfileInstance(self._version, payload) def __repr__(self) -> str: @@ -218,22 +291,18 @@ def __init__(self, version: Version): self._uri = "/ESimProfiles" - def create( + def _create( self, callback_url: Union[str, object] = values.unset, callback_method: Union[str, object] = values.unset, generate_matching_id: Union[bool, object] = values.unset, eid: Union[str, object] = values.unset, - ) -> EsimProfileInstance: + ) -> tuple: """ - Create the EsimProfileInstance + Internal helper for create operation - :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. - :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. - :param generate_matching_id: When set to `true`, a value for `Eid` does not need to be provided. Instead, when the eSIM profile is reserved, a matching ID will be generated and returned via the `matching_id` property. This identifies the specific eSIM profile that can be used by any capable device to claim and download the profile. - :param eid: Identifier of the eUICC that will claim the eSIM Profile. - - :returns: The created EsimProfileInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -246,13 +315,15 @@ def create( ) headers = values.of({"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 EsimProfileInstance(self._version, payload) - - async def create_async( + def create( self, callback_url: Union[str, object] = values.unset, callback_method: Union[str, object] = values.unset, @@ -260,7 +331,7 @@ async def create_async( eid: Union[str, object] = values.unset, ) -> EsimProfileInstance: """ - Asynchronously create the EsimProfileInstance + Create the EsimProfileInstance :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. @@ -269,6 +340,53 @@ async def create_async( :returns: The created EsimProfileInstance """ + payload, _, _ = self._create( + callback_url=callback_url, + callback_method=callback_method, + generate_matching_id=generate_matching_id, + eid=eid, + ) + return EsimProfileInstance(self._version, payload) + + def create_with_http_info( + self, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + generate_matching_id: Union[bool, object] = values.unset, + eid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the EsimProfileInstance and return response metadata + + :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param generate_matching_id: When set to `true`, a value for `Eid` does not need to be provided. Instead, when the eSIM profile is reserved, a matching ID will be generated and returned via the `matching_id` property. This identifies the specific eSIM profile that can be used by any capable device to claim and download the profile. + :param eid: Identifier of the eUICC that will claim the eSIM Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + callback_url=callback_url, + callback_method=callback_method, + generate_matching_id=generate_matching_id, + eid=eid, + ) + instance = EsimProfileInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + generate_matching_id: Union[bool, object] = values.unset, + eid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -280,12 +398,65 @@ async def create_async( ) headers = values.of({"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, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + generate_matching_id: Union[bool, object] = values.unset, + eid: Union[str, object] = values.unset, + ) -> EsimProfileInstance: + """ + Asynchronously create the EsimProfileInstance + + :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param generate_matching_id: When set to `true`, a value for `Eid` does not need to be provided. Instead, when the eSIM profile is reserved, a matching ID will be generated and returned via the `matching_id` property. This identifies the specific eSIM profile that can be used by any capable device to claim and download the profile. + :param eid: Identifier of the eUICC that will claim the eSIM Profile. + + :returns: The created EsimProfileInstance + """ + payload, _, _ = await self._create_async( + callback_url=callback_url, + callback_method=callback_method, + generate_matching_id=generate_matching_id, + eid=eid, + ) return EsimProfileInstance(self._version, payload) + async def create_with_http_info_async( + self, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + generate_matching_id: Union[bool, object] = values.unset, + eid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the EsimProfileInstance and return response metadata + + :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param generate_matching_id: When set to `true`, a value for `Eid` does not need to be provided. Instead, when the eSIM profile is reserved, a matching ID will be generated and returned via the `matching_id` property. This identifies the specific eSIM profile that can be used by any capable device to claim and download the profile. + :param eid: Identifier of the eUICC that will claim the eSIM Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + callback_url=callback_url, + callback_method=callback_method, + generate_matching_id=generate_matching_id, + eid=eid, + ) + instance = EsimProfileInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, eid: Union[str, object] = values.unset, @@ -352,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, @@ -377,6 +612,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( eid=eid, @@ -412,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( @@ -423,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, @@ -456,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( @@ -492,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 2b9fbff44e..7f17059350 100644 --- a/twilio/rest/supersim/v1/fleet.py +++ b/twilio/rest/supersim/v1/fleet.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[FleetContext] = None @property @@ -112,6 +114,24 @@ async def fetch_async(self) -> "FleetInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FleetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FleetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -178,6 +198,72 @@ async def update_async( data_limit=data_limit, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the FleetInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FleetInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -205,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 @@ -212,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: """ @@ -231,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, @@ -266,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, @@ -277,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, @@ -309,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: """ @@ -347,6 +613,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FleetInstance: :param payload: Payload response from the API """ + return FleetInstance(self._version, payload) def __repr__(self) -> str: @@ -371,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, @@ -382,21 +649,12 @@ def create( sms_commands_enabled: Union[bool, object] = values.unset, sms_commands_url: Union[str, object] = values.unset, sms_commands_method: Union[str, object] = values.unset, - ) -> FleetInstance: + ) -> tuple: """ - Create the FleetInstance - - :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. - :param data_enabled: Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. - :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). - :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. - :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. - :param sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `true`. - :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. - :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + Internal helper for create operation - :returns: The created FleetInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -414,13 +672,15 @@ def create( ) headers = values.of({"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 FleetInstance(self._version, payload) - - async def create_async( + def create( self, network_access_profile: str, unique_name: Union[str, object] = values.unset, @@ -433,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. @@ -447,6 +707,78 @@ 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( { @@ -463,12 +795,95 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -527,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, @@ -548,6 +1019,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( network_access_profile=network_access_profile, @@ -577,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( @@ -586,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, @@ -613,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( @@ -643,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 db6ac26432..2af10f7bfb 100644 --- a/twilio/rest/supersim/v1/ip_command.py +++ b/twilio/rest/supersim/v1/ip_command.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -86,6 +87,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[IpCommandContext] = None @property @@ -121,6 +123,24 @@ async def fetch_async(self) -> "IpCommandInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpCommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpCommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -148,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 @@ -155,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: """ @@ -174,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: """ @@ -204,6 +276,7 @@ def get_instance(self, payload: Dict[str, Any]) -> IpCommandInstance: :param payload: Payload response from the API """ + return IpCommandInstance(self._version, payload) def __repr__(self) -> str: @@ -228,7 +301,7 @@ def __init__(self, version: Version): self._uri = "/IpCommands" - def create( + def _create( self, sim: str, payload: str, @@ -236,18 +309,12 @@ def create( payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, callback_url: Union[str, object] = values.unset, callback_method: Union[str, object] = values.unset, - ) -> IpCommandInstance: + ) -> tuple: """ - Create the IpCommandInstance - - :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`. + Internal helper for create operation - :returns: The created IpCommandInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -262,13 +329,15 @@ def create( ) headers = values.of({"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 IpCommandInstance(self._version, payload) - - async def create_async( + def create( self, sim: str, payload: str, @@ -278,7 +347,7 @@ async def create_async( callback_method: Union[str, object] = values.unset, ) -> IpCommandInstance: """ - Asynchronously create the IpCommandInstance + Create the IpCommandInstance :param sim: The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. :param payload: The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. @@ -289,6 +358,63 @@ async def create_async( :returns: The created IpCommandInstance """ + payload, _, _ = self._create( + sim=sim, + payload=payload, + device_port=device_port, + payload_type=payload_type, + callback_url=callback_url, + callback_method=callback_method, + ) + return IpCommandInstance(self._version, payload) + + def create_with_http_info( + self, + sim: str, + payload: str, + device_port: int, + payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the IpCommandInstance and return response metadata + + :param sim: The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. + :param payload: The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. + :param device_port: The device port to which the IP Command will be sent. + :param payload_type: + :param callback_url: The URL we should call using the `callback_method` after we have sent the IP Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be `GET` or `POST`, and the default is `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + sim=sim, + payload=payload, + device_port=device_port, + payload_type=payload_type, + callback_url=callback_url, + callback_method=callback_method, + ) + instance = IpCommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + sim: str, + payload: str, + device_port: int, + payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -302,12 +428,77 @@ async def create_async( ) headers = values.of({"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, + sim: str, + payload: str, + device_port: int, + payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + ) -> IpCommandInstance: + """ + Asynchronously create the IpCommandInstance + + :param sim: The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. + :param payload: The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. + :param device_port: The device port to which the IP Command will be sent. + :param payload_type: + :param callback_url: The URL we should call using the `callback_method` after we have sent the IP Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be `GET` or `POST`, and the default is `POST`. + + :returns: The created IpCommandInstance + """ + payload, _, _ = await self._create_async( + sim=sim, + payload=payload, + device_port=device_port, + payload_type=payload_type, + callback_url=callback_url, + callback_method=callback_method, + ) return IpCommandInstance(self._version, payload) + async def create_with_http_info_async( + self, + sim: str, + payload: str, + device_port: int, + payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the IpCommandInstance and return response metadata + + :param sim: The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. + :param payload: The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. + :param device_port: The device port to which the IP Command will be sent. + :param payload_type: + :param callback_url: The URL we should call using the `callback_method` after we have sent the IP Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be `GET` or `POST`, and the default is `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + sim=sim, + payload=payload, + device_port=device_port, + payload_type=payload_type, + callback_url=callback_url, + callback_method=callback_method, + ) + instance = IpCommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, sim: Union[str, object] = values.unset, @@ -386,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, @@ -413,6 +680,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -451,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( @@ -463,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, @@ -499,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( @@ -538,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 0d4f6a94fd..c89787b807 100644 --- a/twilio/rest/supersim/v1/network.py +++ b/twilio/rest/supersim/v1/network.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[NetworkContext] = None @property @@ -79,6 +81,24 @@ async def fetch_async(self) -> "NetworkInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -106,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 @@ -113,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: """ @@ -132,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: """ @@ -162,6 +234,7 @@ def get_instance(self, payload: Dict[str, Any]) -> NetworkInstance: :param payload: Payload response from the API """ + return NetworkInstance(self._version, payload) def __repr__(self) -> str: @@ -252,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, @@ -277,6 +414,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( iso_country=iso_country, @@ -312,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( @@ -323,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, @@ -356,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( @@ -392,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 4937ac50dd..02c55897e5 100644 --- a/twilio/rest/supersim/v1/network_access_profile/__init__.py +++ b/twilio/rest/supersim/v1/network_access_profile/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[NetworkAccessProfileContext] = None @property @@ -91,6 +93,24 @@ async def fetch_async(self) -> "NetworkAccessProfileInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkAccessProfileInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset ) -> "NetworkAccessProfileInstance": @@ -119,6 +139,34 @@ async def update_async( unique_name=unique_name, ) + def update_with_http_info( + self, unique_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the NetworkAccessProfileInstance with HTTP info + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + ) + + async def update_with_http_info_async( + self, unique_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the NetworkAccessProfileInstance with HTTP info + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + ) + @property def networks(self) -> NetworkAccessProfileNetworkList: """ @@ -155,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 @@ -162,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: """ @@ -181,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 @@ -203,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( @@ -229,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: @@ -275,6 +435,7 @@ def get_instance(self, payload: Dict[str, Any]) -> NetworkAccessProfileInstance: :param payload: Payload response from the API """ + return NetworkAccessProfileInstance(self._version, payload) def __repr__(self) -> str: @@ -299,18 +460,16 @@ def __init__(self, version: Version): self._uri = "/NetworkAccessProfiles" - def create( + def _create( self, unique_name: Union[str, object] = values.unset, networks: Union[List[str], object] = values.unset, - ) -> NetworkAccessProfileInstance: + ) -> tuple: """ - Create the NetworkAccessProfileInstance + Internal helper for create operation - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. - :param networks: List of Network SIDs that this Network Access Profile will allow connections to. - - :returns: The created NetworkAccessProfileInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -321,25 +480,60 @@ def create( ) headers = values.of({"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 NetworkAccessProfileInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: Union[str, object] = values.unset, networks: Union[List[str], object] = values.unset, ) -> NetworkAccessProfileInstance: """ - Asynchronously create the NetworkAccessProfileInstance + Create the NetworkAccessProfileInstance :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. :param networks: List of Network SIDs that this Network Access Profile will allow connections to. :returns: The created NetworkAccessProfileInstance """ + payload, _, _ = self._create(unique_name=unique_name, networks=networks) + return NetworkAccessProfileInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Create the NetworkAccessProfileInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param networks: List of Network SIDs that this Network Access Profile will allow connections to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, networks=networks + ) + instance = NetworkAccessProfileInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -349,12 +543,51 @@ async def create_async( ) headers = values.of({"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, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> NetworkAccessProfileInstance: + """ + Asynchronously create the NetworkAccessProfileInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param networks: List of Network SIDs that this Network Access Profile will allow connections to. + + :returns: The created NetworkAccessProfileInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, networks=networks + ) return NetworkAccessProfileInstance(self._version, payload) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the NetworkAccessProfileInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param networks: List of Network SIDs that this Network Access Profile will allow connections to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, networks=networks + ) + instance = NetworkAccessProfileInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -405,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, @@ -424,6 +707,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -450,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( @@ -458,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, @@ -482,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( @@ -509,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 cbe4d5c0ea..7386d60751 100644 --- a/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py +++ b/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def __init__( "network_access_profile_sid": network_access_profile_sid, "sid": sid or self.sid, } + self._context: Optional[NetworkAccessProfileNetworkContext] = None @property @@ -89,6 +91,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the NetworkAccessProfileNetworkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the NetworkAccessProfileNetworkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "NetworkAccessProfileNetworkInstance": """ Fetch the NetworkAccessProfileNetworkInstance @@ -107,6 +127,24 @@ async def fetch_async(self) -> "NetworkAccessProfileNetworkInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkAccessProfileNetworkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -142,6 +180,20 @@ def __init__(self, version: Version, network_access_profile_sid: str, sid: str): ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the NetworkAccessProfileNetworkInstance @@ -149,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: @@ -161,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: @@ -173,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: """ @@ -193,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: """ @@ -228,6 +364,7 @@ def get_instance( :param payload: Payload response from the API """ + return NetworkAccessProfileNetworkInstance( self._version, payload, @@ -265,13 +402,12 @@ def __init__(self, version: Version, network_access_profile_sid: str): ) ) - def create(self, network: str) -> NetworkAccessProfileNetworkInstance: + def _create(self, network: str) -> tuple: """ - Create the NetworkAccessProfileNetworkInstance - - :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( @@ -281,23 +417,51 @@ def create(self, network: str) -> NetworkAccessProfileNetworkInstance: ) headers = values.of({"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, 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( @@ -307,16 +471,45 @@ async def create_async(self, network: str) -> NetworkAccessProfileNetworkInstanc ) headers = values.of({"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, 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, @@ -367,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, @@ -386,6 +629,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -412,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( @@ -420,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, @@ -444,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, @@ -471,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, self._solution) + return NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NetworkAccessProfileNetworkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with NetworkAccessProfileNetworkPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> NetworkAccessProfileNetworkPage: """ @@ -486,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: """ @@ -498,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 f946150287..8b6f2a03a7 100644 --- a/twilio/rest/supersim/v1/settings_update.py +++ b/twilio/rest/supersim/v1/settings_update.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -77,6 +78,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SettingsUpdateInstance: :param payload: Payload response from the API """ + return SettingsUpdateInstance(self._version, payload) def __repr__(self) -> str: @@ -161,6 +163,66 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SettingsUpdateInstance and returns headers from first page + + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sim=sim, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SettingsUpdateInstance and returns headers from first page + + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sim=sim, status=status, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, sim: Union[str, object] = values.unset, @@ -184,6 +246,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -216,6 +279,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -226,6 +290,68 @@ async def list_async( ) ] + def list_with_http_info( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SettingsUpdateInstance and returns headers from first page + + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sim=sim, + status=status, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SettingsUpdateInstance and returns headers from first page + + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sim=sim, + status=status, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, sim: Union[str, object] = values.unset, @@ -256,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( @@ -289,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 1452f1eac5..16f0046e17 100644 --- a/twilio/rest/supersim/v1/sim/__init__.py +++ b/twilio/rest/supersim/v1/sim/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SimContext] = None @property @@ -109,6 +111,24 @@ async def fetch_async(self) -> "SimInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -169,6 +189,66 @@ async def update_async( account_sid=account_sid, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SimInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + @property def billing_periods(self) -> BillingPeriodList: """ @@ -213,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 @@ -220,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: """ @@ -239,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, @@ -272,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, @@ -282,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, @@ -312,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: @@ -373,6 +623,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SimInstance: :param payload: Payload response from the API """ + return SimInstance(self._version, payload) def __repr__(self) -> str: @@ -397,14 +648,12 @@ def __init__(self, version: Version): self._uri = "/Sims" - def create(self, iccid: str, registration_code: str) -> SimInstance: + def _create(self, iccid: str, registration_code: str) -> tuple: """ - Create the SimInstance + Internal helper for create operation - :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the Super SIM to be added to your Account. - :param registration_code: The 10-digit code required to claim the Super SIM for your Account. - - :returns: The created SimInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -415,20 +664,47 @@ def create(self, iccid: str, registration_code: str) -> SimInstance: ) headers = values.of({"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, 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( @@ -439,12 +715,45 @@ async def create_async(self, iccid: str, registration_code: str) -> SimInstance: ) headers = values.of({"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, 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, @@ -511,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, @@ -536,6 +909,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -571,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( @@ -582,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, @@ -615,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( @@ -651,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 e6fb961835..90a0e13d3d 100644 --- a/twilio/rest/supersim/v1/sim/billing_period.py +++ b/twilio/rest/supersim/v1/sim/billing_period.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -83,6 +84,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BillingPeriodInstance: :param payload: Payload response from the API """ + return BillingPeriodInstance( self._version, payload, sim_sid=self._solution["sim_sid"] ) @@ -164,6 +166,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams BillingPeriodInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams BillingPeriodInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -183,6 +235,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -209,6 +262,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -217,6 +271,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists BillingPeriodInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists BillingPeriodInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -241,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, @@ -268,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: """ @@ -283,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: """ @@ -295,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 7c2b70e50f..9d67476a36 100644 --- a/twilio/rest/supersim/v1/sim/sim_ip_address.py +++ b/twilio/rest/supersim/v1/sim/sim_ip_address.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SimIpAddressInstance: :param payload: Payload response from the API """ + return SimIpAddressInstance( self._version, payload, sim_sid=self._solution["sim_sid"] ) @@ -143,6 +145,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams SimIpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams SimIpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -162,6 +214,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -188,6 +241,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -196,6 +250,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists SimIpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists SimIpAddressInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -220,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, @@ -247,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: """ @@ -262,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: """ @@ -274,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 26d39a0bf8..3b4ce6558d 100644 --- a/twilio/rest/supersim/v1/sms_command.py +++ b/twilio/rest/supersim/v1/sms_command.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -71,6 +72,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SmsCommandContext] = None @property @@ -106,6 +108,24 @@ async def fetch_async(self) -> "SmsCommandInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SmsCommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SmsCommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -133,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 @@ -140,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: """ @@ -159,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: """ @@ -189,6 +261,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SmsCommandInstance: :param payload: Payload response from the API """ + return SmsCommandInstance(self._version, payload) def __repr__(self) -> str: @@ -213,22 +286,18 @@ def __init__(self, version: Version): self._uri = "/SmsCommands" - def create( + def _create( self, sim: str, payload: str, callback_method: Union[str, object] = values.unset, callback_url: Union[str, object] = values.unset, - ) -> SmsCommandInstance: + ) -> tuple: """ - Create the SmsCommandInstance + Internal helper for create operation - :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. - :param payload: The message body of the SMS Command. - :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. - :param callback_url: The URL we should call using the `callback_method` after we have sent the command. - - :returns: The created SmsCommandInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -241,13 +310,15 @@ def create( ) headers = values.of({"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 SmsCommandInstance(self._version, payload) - - async def create_async( + def create( self, sim: str, payload: str, @@ -255,7 +326,7 @@ async def create_async( callback_url: Union[str, object] = values.unset, ) -> SmsCommandInstance: """ - Asynchronously create the SmsCommandInstance + Create the SmsCommandInstance :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. :param payload: The message body of the SMS Command. @@ -264,6 +335,53 @@ async def create_async( :returns: The created SmsCommandInstance """ + payload, _, _ = self._create( + sim=sim, + payload=payload, + callback_method=callback_method, + callback_url=callback_url, + ) + return SmsCommandInstance(self._version, payload) + + def create_with_http_info( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the SmsCommandInstance and return response metadata + + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. + :param payload: The message body of the SMS Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param callback_url: The URL we should call using the `callback_method` after we have sent the command. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + sim=sim, + payload=payload, + callback_method=callback_method, + callback_url=callback_url, + ) + instance = SmsCommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -275,12 +393,65 @@ async def create_async( ) headers = values.of({"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, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> SmsCommandInstance: + """ + Asynchronously create the SmsCommandInstance + + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. + :param payload: The message body of the SMS Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param callback_url: The URL we should call using the `callback_method` after we have sent the command. + + :returns: The created SmsCommandInstance + """ + payload, _, _ = await self._create_async( + sim=sim, + payload=payload, + callback_method=callback_method, + callback_url=callback_url, + ) return SmsCommandInstance(self._version, payload) + async def create_with_http_info_async( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SmsCommandInstance and return response metadata + + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. + :param payload: The message body of the SMS Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param callback_url: The URL we should call using the `callback_method` after we have sent the command. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + sim=sim, + payload=payload, + callback_method=callback_method, + callback_url=callback_url, + ) + instance = SmsCommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, sim: Union[str, object] = values.unset, @@ -347,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, @@ -372,6 +607,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -407,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( @@ -418,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, @@ -451,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( @@ -487,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 86a335d0de..05547f6d64 100644 --- a/twilio/rest/supersim/v1/usage_record.py +++ b/twilio/rest/supersim/v1/usage_record.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: :param payload: Payload response from the API """ + return UsageRecordInstance(self._version, payload) def __repr__(self) -> str: @@ -210,6 +212,106 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UsageRecordInstance and returns headers from first page + + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UsageRecordInstance and returns headers from first page + + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, sim: Union[str, object] = values.unset, @@ -245,6 +347,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -295,6 +398,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -311,6 +415,104 @@ async def list_async( ) ] + def list_with_http_info( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UsageRecordInstance and returns headers from first page + + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UsageRecordInstance and returns headers from first page + + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, sim: Union[str, object] = values.unset, @@ -359,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( @@ -410,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/v1/service/__init__.py b/twilio/rest/sync/v1/service/__init__.py index 02d4e8f7e0..a376ed7982 100644 --- a/twilio/rest/sync/v1/service/__init__.py +++ b/twilio/rest/sync/v1/service/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -114,6 +116,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -132,6 +152,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, webhook_url: Union[str, object] = values.unset, @@ -198,6 +236,72 @@ async def update_async( webhooks_from_rest_enabled=webhooks_from_rest_enabled, ) + def update_with_http_info( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + + async def update_with_http_info_async( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + @property def documents(self) -> DocumentList: """ @@ -258,6 +362,20 @@ def __init__(self, version: Version, sid: str): self._sync_maps: Optional[SyncMapList] = None self._sync_streams: Optional[SyncStreamList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ServiceInstance @@ -265,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: @@ -277,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: @@ -289,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: """ @@ -308,19 +498,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, webhook_url: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -329,20 +529,14 @@ def update( reachability_debouncing_enabled: Union[bool, object] = values.unset, reachability_debouncing_window: Union[int, object] = values.unset, webhooks_from_rest_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Update the ServiceInstance - - :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`. + Internal helper for update operation - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "WebhookUrl": webhook_url, @@ -360,16 +554,17 @@ def update( ), } ) + 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, webhook_url: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -380,7 +575,7 @@ async def update_async( webhooks_from_rest_enabled: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Asynchronous coroutine to update the ServiceInstance + Update the ServiceInstance :param webhook_url: The URL we should call when Sync objects are manipulated. :param friendly_name: A string that you assign to describe the resource. @@ -392,6 +587,69 @@ async def update_async( :returns: The updated ServiceInstance """ + payload, _, _ = self._update( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "WebhookUrl": webhook_url, @@ -409,43 +667,113 @@ 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" - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + headers["Accept"] = "application/json" - @property - def documents(self) -> DocumentList: - """ - Access the documents - """ - if self._documents is None: - self._documents = DocumentList( - self._version, - self._solution["sid"], - ) - return self._documents + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def sync_lists(self) -> SyncListList: - """ - Access the sync_lists + async def update_async( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: """ - if self._sync_lists is None: - self._sync_lists = SyncListList( - self._version, - self._solution["sid"], - ) - return self._sync_lists + Asynchronous coroutine to update the ServiceInstance - @property - def sync_maps(self) -> SyncMapList: - """ - Access the sync_maps + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The updated ServiceInstance + """ + payload, _, _ = await self._update_async( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance and return response metadata + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def documents(self) -> DocumentList: + """ + 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( @@ -484,6 +812,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -508,7 +837,7 @@ def __init__(self, version: Version): self._uri = "/Services" - def create( + def _create( self, friendly_name: Union[str, object] = values.unset, webhook_url: Union[str, object] = values.unset, @@ -517,19 +846,12 @@ def create( reachability_debouncing_enabled: Union[bool, object] = values.unset, reachability_debouncing_window: Union[int, object] = values.unset, webhooks_from_rest_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Create the ServiceInstance - - :param friendly_name: A string that you assign to describe the resource. - :param webhook_url: The URL we should call when Sync objects are manipulated. - :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. - :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. - :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. - :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. - :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + Internal helper for create operation - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -551,13 +873,15 @@ def create( ) headers = values.of({"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 ServiceInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: Union[str, object] = values.unset, webhook_url: Union[str, object] = values.unset, @@ -568,7 +892,7 @@ async def create_async( webhooks_from_rest_enabled: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Asynchronously create the ServiceInstance + Create the ServiceInstance :param friendly_name: A string that you assign to describe the resource. :param webhook_url: The URL we should call when Sync objects are manipulated. @@ -580,6 +904,68 @@ async def create_async( :returns: The created ServiceInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + webhook_url=webhook_url, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param friendly_name: A string that you assign to describe the resource. + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + webhook_url=webhook_url, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -600,12 +986,83 @@ async def create_async( ) headers = values.of({"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, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A string that you assign to describe the resource. + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The created ServiceInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + webhook_url=webhook_url, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) return ServiceInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ServiceInstance and return response metadata + + :param friendly_name: A string that you assign to describe the resource. + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + webhook_url=webhook_url, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -656,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, @@ -675,6 +1182,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -701,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( @@ -709,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, @@ -733,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( @@ -760,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 033f27cf42..3611fe0d18 100644 --- a/twilio/rest/sync/v1/service/document/__init__.py +++ b/twilio/rest/sync/v1/service/document/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -73,6 +74,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[DocumentContext] = None @property @@ -109,6 +111,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "DocumentInstance": """ Fetch the DocumentInstance @@ -127,6 +147,24 @@ async def fetch_async(self) -> "DocumentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -169,6 +207,48 @@ async def update_async( ttl=ttl, ) + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the DocumentInstance with HTTP info + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + data=data, + ttl=ttl, + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DocumentInstance with HTTP info + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + data=data, + ttl=ttl, + ) + @property def document_permissions(self) -> DocumentPermissionList: """ @@ -207,6 +287,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._document_permissions: Optional[DocumentPermissionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the DocumentInstance @@ -214,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: @@ -226,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: @@ -238,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: """ @@ -258,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 - - :param if_match: The If-Match HTTP request header - :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. - :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + Internal helper for update operation - :returns: The updated DocumentInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "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 - 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, + 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, @@ -309,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, @@ -347,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: """ @@ -378,6 +646,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DocumentInstance: :param payload: Payload response from the API """ + return DocumentInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -409,20 +678,17 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Documents".format(**self._solution) - def create( + def _create( self, unique_name: Union[str, object] = values.unset, data: Union[object, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> DocumentInstance: + ) -> tuple: """ - Create the DocumentInstance + Internal helper for create operation - :param unique_name: An application-defined string that uniquely identifies the Sync Document - :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. - :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). - - :returns: The created DocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -434,28 +700,68 @@ def create( ) headers = values.of({"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, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Create the DocumentInstance + + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: The created DocumentInstance + """ + payload, _, _ = self._create(unique_name=unique_name, data=data, ttl=ttl) return DocumentInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, unique_name: Union[str, object] = values.unset, data: Union[object, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> DocumentInstance: + ) -> ApiResponse: """ - Asynchronously create the DocumentInstance + Create the DocumentInstance and return response metadata :param unique_name: An application-defined string that uniquely identifies the Sync Document :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). - :returns: The created DocumentInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, data=data, ttl=ttl + ) + instance = DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -467,14 +773,59 @@ async def create_async( ) headers = values.of({"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, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Asynchronously create the DocumentInstance + + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: The created DocumentInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, data=data, ttl=ttl + ) return DocumentInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the DocumentInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, data=data, ttl=ttl + ) + instance = DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -525,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, @@ -544,6 +945,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -570,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( @@ -578,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, @@ -602,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, @@ -629,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: """ @@ -644,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: """ @@ -656,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 40f524832c..16f87b9cd1 100644 --- a/twilio/rest/sync/v1/service/document/document_permission.py +++ b/twilio/rest/sync/v1/service/document/document_permission.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( "document_sid": document_sid, "identity": identity or self.identity, } + self._context: Optional[DocumentPermissionContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the DocumentPermissionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DocumentPermissionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "DocumentPermissionInstance": """ Fetch the DocumentPermissionInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "DocumentPermissionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DocumentPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DocumentPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, read: bool, write: bool, manage: bool ) -> "DocumentPermissionInstance": @@ -148,6 +186,42 @@ async def update_async( manage=manage, ) + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the DocumentPermissionInstance with HTTP info + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + read=read, + write=write, + manage=manage, + ) + + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DocumentPermissionInstance with HTTP info + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + read=read, + write=write, + manage=manage, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -183,6 +257,20 @@ def __init__( **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the DocumentPermissionInstance @@ -190,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: @@ -202,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: @@ -214,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: """ @@ -235,12 +397,7 @@ 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, @@ -249,18 +406,31 @@ async def fetch_async(self) -> DocumentPermissionInstance: identity=self._solution["identity"], ) - def update( - self, read: bool, write: bool, manage: bool - ) -> DocumentPermissionInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the DocumentPermissionInstance + Asynchronous coroutine to fetch the DocumentPermissionInstance and return response metadata - :param read: Whether the identity can read the Sync Document. Default value is `false`. - :param write: Whether the identity can update the Sync Document. Default value is `false`. - :param manage: Whether the identity can delete the Sync Document. Default value is `false`. - :returns: The updated DocumentPermissionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, read: bool, write: bool, manage: bool) -> tuple: """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "Read": serialize.boolean_to_string(read), @@ -268,13 +438,29 @@ def update( "Manage": serialize.boolean_to_string(manage), } ) + 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, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: + """ + Update the DocumentPermissionInstance + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance + """ + payload, _, _ = self._update(read=read, write=write, manage=manage) return DocumentPermissionInstance( self._version, payload, @@ -283,18 +469,38 @@ def update( identity=self._solution["identity"], ) - async def update_async( + def update_with_http_info( self, read: bool, write: bool, manage: bool - ) -> DocumentPermissionInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the DocumentPermissionInstance + Update the DocumentPermissionInstance and return response metadata :param read: Whether the identity can read the Sync Document. Default value is `false`. :param write: Whether the identity can update the Sync Document. Default value is `false`. :param manage: Whether the identity can delete the Sync Document. Default value is `false`. - :returns: The updated DocumentPermissionInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._update( + read=read, write=write, manage=manage + ) + instance = DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "Read": serialize.boolean_to_string(read), @@ -302,13 +508,29 @@ async def update_async( "Manage": serialize.boolean_to_string(manage), } ) + 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, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: + """ + Asynchronous coroutine to update the DocumentPermissionInstance + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance + """ + payload, _, _ = await self._update_async(read=read, write=write, manage=manage) return DocumentPermissionInstance( self._version, payload, @@ -317,6 +539,30 @@ async def update_async( identity=self._solution["identity"], ) + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the DocumentPermissionInstance and return response metadata + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + read=read, write=write, manage=manage + ) + instance = DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -335,6 +581,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DocumentPermissionInstance: :param payload: Payload response from the API """ + return DocumentPermissionInstance( self._version, payload, @@ -425,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, @@ -444,6 +741,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -470,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( @@ -478,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, @@ -502,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, @@ -529,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: """ @@ -544,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: """ @@ -556,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 235fcbd1b9..e757173ab9 100644 --- a/twilio/rest/sync/v1/service/sync_list/__init__.py +++ b/twilio/rest/sync/v1/service/sync_list/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[SyncListContext] = None @property @@ -108,6 +110,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SyncListInstance": """ Fetch the SyncListInstance @@ -126,6 +146,24 @@ async def fetch_async(self) -> "SyncListInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, ttl: Union[int, object] = values.unset, @@ -162,6 +200,42 @@ async def update_async( collection_ttl=collection_ttl, ) + def update_with_http_info( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the SyncListInstance with HTTP info + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + async def update_with_http_info_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListInstance with HTTP info + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) + @property def sync_list_items(self) -> SyncListItemList: """ @@ -208,6 +282,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._sync_list_items: Optional[SyncListItemList] = None self._sync_list_permissions: Optional[SyncListPermissionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SyncListInstance @@ -215,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: @@ -227,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: @@ -239,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: """ @@ -259,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, @@ -305,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" - 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, + 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, @@ -338,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: """ @@ -382,6 +634,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SyncListInstance: :param payload: Payload response from the API """ + return SyncListInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -413,20 +666,17 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Lists".format(**self._solution) - def create( + def _create( self, unique_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncListInstance: + ) -> tuple: """ - Create the SyncListInstance - - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. - :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. - :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + Internal helper for create operation - :returns: The created SyncListInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -438,28 +688,70 @@ def create( ) headers = values.of({"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, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Create the SyncListInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListInstance + """ + payload, _, _ = self._create( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) return SyncListInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, unique_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncListInstance: + ) -> ApiResponse: """ - Asynchronously create the SyncListInstance + Create the SyncListInstance and return response metadata :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. - :returns: The created SyncListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -471,14 +763,59 @@ async def create_async( ) headers = values.of({"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, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Asynchronously create the SyncListInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) return SyncListInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SyncListInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -529,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, @@ -548,6 +935,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -574,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( @@ -582,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, @@ -606,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, @@ -633,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: """ @@ -648,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: """ @@ -660,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 0db046e1a8..40dfcbadf9 100644 --- a/twilio/rest/sync/v1/service/sync_list/sync_list_item.py +++ b/twilio/rest/sync/v1/service/sync_list/sync_list_item.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( "list_sid": list_sid, "index": index or self.index, } + self._context: Optional[SyncListItemContext] = None @property @@ -122,6 +124,34 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo if_match=if_match, ) + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the SyncListItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + if_match=if_match, + ) + + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + if_match=if_match, + ) + def fetch(self) -> "SyncListItemInstance": """ Fetch the SyncListItemInstance @@ -140,6 +170,24 @@ async def fetch_async(self) -> "SyncListItemInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncListItemInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncListItemInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -194,6 +242,60 @@ async def update_async( collection_ttl=collection_ttl, ) + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the SyncListItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -227,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 @@ -235,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: """ @@ -251,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: @@ -268,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: """ @@ -289,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), @@ -330,25 +536,22 @@ def update( "CollectionTtl": collection_ttl, } ) - headers = values.of( - { - "If-Match": if_match, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match - return SyncListItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - list_sid=self._solution["list_sid"], - index=self._solution["index"], + 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, if_match: Union[str, object] = values.unset, data: Union[object, object] = values.unset, @@ -357,7 +560,7 @@ async def update_async( collection_ttl: Union[int, object] = values.unset, ) -> SyncListItemInstance: """ - Asynchronous coroutine to update the 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. @@ -367,24 +570,13 @@ async def update_async( :returns: The updated SyncListItemInstance """ - data = values.of( - { - "Data": serialize.object(data), - "Ttl": ttl, - "ItemTtl": item_ttl, - "CollectionTtl": collection_ttl, - } - ) - headers = values.of( - { - "If-Match": if_match, - } - ) - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, ) - return SyncListItemInstance( self._version, payload, @@ -393,48 +585,191 @@ async def update_async( index=self._solution["index"], ) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation + 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: """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) + 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. -class SyncListItemPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> SyncListItemInstance: - """ - Build an instance of SyncListItemInstance - - :param payload: Payload response from the API + :returns: ApiResponse with instance, status code, and headers """ - return SyncListItemInstance( + 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) - def __repr__(self) -> str: + 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: """ - Provide a friendly representation + Internal async helper for update operation - :returns: Machine friendly representation + Returns: + tuple: (payload, status_code, headers) """ - return "" + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) -class SyncListItemList(ListResource): + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match - def __init__(self, version: Version, service_sid: str, list_sid: str): - """ - Initialize the SyncListItemList + headers["Content-Type"] = "application/x-www-form-urlencoded" - :param version: Version that contains the resource - :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the List Item resources to read. + 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, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListItemInstance and return response metadata + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def __repr__(self) -> str: + """ + 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: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the List Item resources to read. :param list_sid: The SID of the Sync List with the List Items to read. Can be the Sync List resource's `sid` or its `unique_name`. """ @@ -449,22 +784,18 @@ def __init__(self, version: Version, service_sid: str, list_sid: str): **self._solution ) - def create( + def _create( self, data: object, ttl: Union[int, object] = values.unset, item_ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncListItemInstance: + ) -> tuple: """ - Create the SyncListItemInstance - - :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. - :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. - :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. - :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. + Internal helper for create operation - :returns: The created SyncListItemInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -477,10 +808,34 @@ def create( ) headers = values.of({"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, + 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, @@ -488,22 +843,46 @@ def create( list_sid=self._solution["list_sid"], ) - async def create_async( + def create_with_http_info( self, data: object, ttl: Union[int, object] = values.unset, item_ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncListItemInstance: + ) -> ApiResponse: """ - Asynchronously create the SyncListItemInstance + Create the SyncListItemInstance and return response metadata :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. - :returns: The created SyncListItemInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + data=data, ttl=ttl, item_ttl=item_ttl, collection_ttl=collection_ttl + ) + instance = SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -516,10 +895,34 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -527,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, @@ -593,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, @@ -618,6 +1113,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -653,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( @@ -664,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, @@ -697,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, @@ -733,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: """ @@ -748,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: """ @@ -760,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 07fce14b95..620954de44 100644 --- a/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py +++ b/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( "list_sid": list_sid, "identity": identity or self.identity, } + self._context: Optional[SyncListPermissionContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncListPermissionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListPermissionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SyncListPermissionInstance": """ Fetch the SyncListPermissionInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "SyncListPermissionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncListPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncListPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, read: bool, write: bool, manage: bool ) -> "SyncListPermissionInstance": @@ -148,6 +186,42 @@ async def update_async( manage=manage, ) + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the SyncListPermissionInstance with HTTP info + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + read=read, + write=write, + manage=manage, + ) + + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListPermissionInstance with HTTP info + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + read=read, + write=write, + manage=manage, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -185,6 +259,20 @@ def __init__( ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SyncListPermissionInstance @@ -192,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: @@ -204,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: @@ -216,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: """ @@ -237,12 +399,7 @@ 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, @@ -251,18 +408,31 @@ async def fetch_async(self) -> SyncListPermissionInstance: identity=self._solution["identity"], ) - def update( - self, read: bool, write: bool, manage: bool - ) -> SyncListPermissionInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the SyncListPermissionInstance + Asynchronous coroutine to fetch the SyncListPermissionInstance and return response metadata - :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. - :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. - :param manage: Whether the identity can delete the Sync List. Default value is `false`. - :returns: The updated SyncListPermissionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, read: bool, write: bool, manage: bool) -> tuple: """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "Read": serialize.boolean_to_string(read), @@ -270,13 +440,29 @@ def update( "Manage": serialize.boolean_to_string(manage), } ) + 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, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: + """ + Update the SyncListPermissionInstance + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance + """ + payload, _, _ = self._update(read=read, write=write, manage=manage) return SyncListPermissionInstance( self._version, payload, @@ -285,18 +471,38 @@ def update( identity=self._solution["identity"], ) - async def update_async( + def update_with_http_info( self, read: bool, write: bool, manage: bool - ) -> SyncListPermissionInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SyncListPermissionInstance + Update the SyncListPermissionInstance and return response metadata :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. :param manage: Whether the identity can delete the Sync List. Default value is `false`. - :returns: The updated SyncListPermissionInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._update( + read=read, write=write, manage=manage + ) + instance = SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "Read": serialize.boolean_to_string(read), @@ -304,13 +510,29 @@ async def update_async( "Manage": serialize.boolean_to_string(manage), } ) + 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, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: + """ + Asynchronous coroutine to update the SyncListPermissionInstance + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance + """ + payload, _, _ = await self._update_async(read=read, write=write, manage=manage) return SyncListPermissionInstance( self._version, payload, @@ -319,6 +541,30 @@ async def update_async( identity=self._solution["identity"], ) + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncListPermissionInstance and return response metadata + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + read=read, write=write, manage=manage + ) + instance = SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -337,6 +583,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SyncListPermissionInstance: :param payload: Payload response from the API """ + return SyncListPermissionInstance( self._version, payload, @@ -425,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, @@ -444,6 +741,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -470,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( @@ -478,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, @@ -502,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, @@ -529,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: """ @@ -544,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: """ @@ -556,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 1c6b5c9a00..1c5049b798 100644 --- a/twilio/rest/sync/v1/service/sync_map/__init__.py +++ b/twilio/rest/sync/v1/service/sync_map/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[SyncMapContext] = None @property @@ -108,6 +110,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncMapInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SyncMapInstance": """ Fetch the SyncMapInstance @@ -126,6 +146,24 @@ async def fetch_async(self) -> "SyncMapInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncMapInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncMapInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, ttl: Union[int, object] = values.unset, @@ -162,6 +200,42 @@ async def update_async( collection_ttl=collection_ttl, ) + def update_with_http_info( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the SyncMapInstance with HTTP info + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + async def update_with_http_info_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncMapInstance with HTTP info + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) + @property def sync_map_items(self) -> SyncMapItemList: """ @@ -208,6 +282,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._sync_map_items: Optional[SyncMapItemList] = None self._sync_map_permissions: Optional[SyncMapPermissionList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SyncMapInstance @@ -215,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: @@ -227,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: @@ -239,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: """ @@ -259,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, @@ -305,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" - 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, + 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, @@ -338,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: """ @@ -382,6 +634,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SyncMapInstance: :param payload: Payload response from the API """ + return SyncMapInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -413,20 +666,17 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Maps".format(**self._solution) - def create( + def _create( self, unique_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncMapInstance: + ) -> tuple: """ - Create the SyncMapInstance - - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. - :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. - :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + Internal helper for create operation - :returns: The created SyncMapInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -438,28 +688,70 @@ def create( ) headers = values.of({"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, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Create the SyncMapInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapInstance + """ + payload, _, _ = self._create( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) return SyncMapInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, unique_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncMapInstance: + ) -> ApiResponse: """ - Asynchronously create the SyncMapInstance + Create the SyncMapInstance and return response metadata :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. - :returns: The created SyncMapInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -471,14 +763,59 @@ async def create_async( ) headers = values.of({"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, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Asynchronously create the SyncMapInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) return SyncMapInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SyncMapInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl + ) + instance = SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -529,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, @@ -548,6 +935,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -574,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( @@ -582,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, @@ -606,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, @@ -633,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: """ @@ -648,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: """ @@ -660,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 c5381fc592..e63720c278 100644 --- a/twilio/rest/sync/v1/service/sync_map/sync_map_item.py +++ b/twilio/rest/sync/v1/service/sync_map/sync_map_item.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -79,6 +80,7 @@ def __init__( "map_sid": map_sid, "key": key or self.key, } + self._context: Optional[SyncMapItemContext] = None @property @@ -122,6 +124,34 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo if_match=if_match, ) + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the SyncMapItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + if_match=if_match, + ) + + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + if_match=if_match, + ) + def fetch(self) -> "SyncMapItemInstance": """ Fetch the SyncMapItemInstance @@ -140,6 +170,24 @@ async def fetch_async(self) -> "SyncMapItemInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncMapItemInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncMapItemInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -194,6 +242,60 @@ async def update_async( collection_ttl=collection_ttl, ) + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the SyncMapItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncMapItemInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -227,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 @@ -235,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: """ @@ -251,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: @@ -268,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: """ @@ -289,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), @@ -330,25 +536,22 @@ def update( "CollectionTtl": collection_ttl, } ) - headers = values.of( - { - "If-Match": if_match, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match - return SyncMapItemInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - map_sid=self._solution["map_sid"], - key=self._solution["key"], + 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, if_match: Union[str, object] = values.unset, data: Union[object, object] = values.unset, @@ -357,7 +560,7 @@ async def update_async( collection_ttl: Union[int, object] = values.unset, ) -> SyncMapItemInstance: """ - Asynchronous coroutine to update the 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. @@ -367,24 +570,13 @@ async def update_async( :returns: The updated SyncMapItemInstance """ - data = values.of( - { - "Data": serialize.object(data), - "Ttl": ttl, - "ItemTtl": item_ttl, - "CollectionTtl": collection_ttl, - } - ) - headers = values.of( - { - "If-Match": if_match, - } - ) - - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = self._update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, ) - return SyncMapItemInstance( self._version, payload, @@ -393,48 +585,191 @@ async def update_async( key=self._solution["key"], ) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation + 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: """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) + Update the SyncMapItemInstance and return response metadata + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. -class SyncMapItemPage(Page): - - def get_instance(self, payload: Dict[str, Any]) -> SyncMapItemInstance: - """ - Build an instance of SyncMapItemInstance - - :param payload: Payload response from the API + :returns: ApiResponse with instance, status code, and headers """ - return SyncMapItemInstance( + 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) - def __repr__(self) -> str: + 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: """ - Provide a friendly representation + Internal async helper for update operation - :returns: Machine friendly representation + Returns: + tuple: (payload, status_code, headers) """ - return "" + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) -class SyncMapItemList(ListResource): + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match - def __init__(self, version: Version, service_sid: str, map_sid: str): - """ - Initialize the SyncMapItemList + headers["Content-Type"] = "application/x-www-form-urlencoded" - :param version: Version that contains the resource - :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Map Item resources to read. + 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, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + + 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 + """ + 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: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Map Item resources to read. :param map_sid: The SID of the Sync Map with the Sync Map Item resource to fetch. Can be the Sync Map resource's `sid` or its `unique_name`. """ @@ -449,24 +784,19 @@ def __init__(self, version: Version, service_sid: str, map_sid: str): **self._solution ) - def create( + def _create( self, key: str, data: object, ttl: Union[int, object] = values.unset, item_ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncMapItemInstance: + ) -> tuple: """ - Create the SyncMapItemInstance + Internal helper for create operation - :param key: The unique, user-defined key for the Map Item. Can be up to 320 characters long. - :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. - :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. - :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. - :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. - - :returns: The created SyncMapItemInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -480,10 +810,40 @@ def create( ) headers = values.of({"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, + 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, @@ -491,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. @@ -508,7 +868,36 @@ async def create_async( :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. - :returns: The created SyncMapItemInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + key=key, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + instance = SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + key: str, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -522,10 +911,40 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -533,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, @@ -599,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, @@ -624,6 +1141,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -659,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( @@ -670,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, @@ -703,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, @@ -739,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: """ @@ -754,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: """ @@ -766,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 ba056906c7..eb210e017b 100644 --- a/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py +++ b/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( "map_sid": map_sid, "identity": identity or self.identity, } + self._context: Optional[SyncMapPermissionContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncMapPermissionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapPermissionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SyncMapPermissionInstance": """ Fetch the SyncMapPermissionInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "SyncMapPermissionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncMapPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncMapPermissionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, read: bool, write: bool, manage: bool ) -> "SyncMapPermissionInstance": @@ -148,6 +186,42 @@ async def update_async( manage=manage, ) + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the SyncMapPermissionInstance with HTTP info + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + read=read, + write=write, + manage=manage, + ) + + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncMapPermissionInstance with HTTP info + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + read=read, + write=write, + manage=manage, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -183,6 +257,20 @@ def __init__(self, version: Version, service_sid: str, map_sid: str, identity: s ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SyncMapPermissionInstance @@ -190,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: @@ -202,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: @@ -214,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: """ @@ -235,12 +397,7 @@ 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, @@ -249,18 +406,31 @@ async def fetch_async(self) -> SyncMapPermissionInstance: identity=self._solution["identity"], ) - def update( - self, read: bool, write: bool, manage: bool - ) -> SyncMapPermissionInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the SyncMapPermissionInstance + Asynchronous coroutine to fetch the SyncMapPermissionInstance and return response metadata - :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. - :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. - :param manage: Whether the identity can delete the Sync Map. Default value is `false`. - :returns: The updated SyncMapPermissionInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, read: bool, write: bool, manage: bool) -> tuple: """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "Read": serialize.boolean_to_string(read), @@ -268,13 +438,29 @@ def update( "Manage": serialize.boolean_to_string(manage), } ) + 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, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: + """ + Update the SyncMapPermissionInstance + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance + """ + payload, _, _ = self._update(read=read, write=write, manage=manage) return SyncMapPermissionInstance( self._version, payload, @@ -283,18 +469,38 @@ def update( identity=self._solution["identity"], ) - async def update_async( + def update_with_http_info( self, read: bool, write: bool, manage: bool - ) -> SyncMapPermissionInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the SyncMapPermissionInstance + Update the SyncMapPermissionInstance and return response metadata :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. :param manage: Whether the identity can delete the Sync Map. Default value is `false`. - :returns: The updated SyncMapPermissionInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._update( + read=read, write=write, manage=manage + ) + instance = SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, read: bool, write: bool, manage: bool) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "Read": serialize.boolean_to_string(read), @@ -302,13 +508,29 @@ async def update_async( "Manage": serialize.boolean_to_string(manage), } ) + 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, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: + """ + Asynchronous coroutine to update the SyncMapPermissionInstance + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance + """ + payload, _, _ = await self._update_async(read=read, write=write, manage=manage) return SyncMapPermissionInstance( self._version, payload, @@ -317,6 +539,30 @@ async def update_async( identity=self._solution["identity"], ) + async def update_with_http_info_async( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncMapPermissionInstance and return response metadata + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + read=read, write=write, manage=manage + ) + instance = SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation @@ -335,6 +581,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SyncMapPermissionInstance: :param payload: Payload response from the API """ + return SyncMapPermissionInstance( self._version, payload, @@ -423,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, @@ -442,6 +739,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -468,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( @@ -476,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, @@ -500,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, @@ -527,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: """ @@ -542,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: """ @@ -554,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 c9b98ab7d0..f233231d44 100644 --- a/twilio/rest/sync/v1/service/sync_stream/__init__.py +++ b/twilio/rest/sync/v1/service/sync_stream/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[SyncStreamContext] = None @property @@ -103,6 +105,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SyncStreamInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncStreamInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SyncStreamInstance": """ Fetch the SyncStreamInstance @@ -121,6 +141,24 @@ async def fetch_async(self) -> "SyncStreamInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncStreamInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncStreamInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, ttl: Union[int, object] = values.unset) -> "SyncStreamInstance": """ Update the SyncStreamInstance @@ -147,6 +185,34 @@ async def update_async( ttl=ttl, ) + def update_with_http_info( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Update the SyncStreamInstance with HTTP info + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + ttl=ttl, + ) + + async def update_with_http_info_async( + self, ttl: Union[int, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SyncStreamInstance with HTTP info + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + ttl=ttl, + ) + @property def stream_messages(self) -> StreamMessageList: """ @@ -185,6 +251,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._stream_messages: Optional[StreamMessageList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SyncStreamInstance @@ -192,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: @@ -204,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: @@ -216,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: """ @@ -236,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, @@ -249,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" + + 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) -> 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, @@ -276,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({}) - 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, 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, @@ -305,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: """ @@ -336,6 +562,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SyncStreamInstance: :param payload: Payload response from the API """ + return SyncStreamInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -367,18 +594,16 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Streams".format(**self._solution) - def create( + def _create( self, unique_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> SyncStreamInstance: + ) -> tuple: """ - Create the SyncStreamInstance + Internal helper for create operation - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. - :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). - - :returns: The created SyncStreamInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -389,26 +614,61 @@ def create( ) headers = values.of({"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, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> SyncStreamInstance: + """ + Create the SyncStreamInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The created SyncStreamInstance + """ + payload, _, _ = self._create(unique_name=unique_name, ttl=ttl) return SyncStreamInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, unique_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> SyncStreamInstance: + ) -> ApiResponse: """ - Asynchronously create the SyncStreamInstance + Create the SyncStreamInstance and return response metadata :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). - :returns: The created SyncStreamInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(unique_name=unique_name, ttl=ttl) + instance = SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -419,14 +679,53 @@ async def create_async( ) headers = values.of({"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, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> SyncStreamInstance: + """ + Asynchronously create the SyncStreamInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The created SyncStreamInstance + """ + payload, _, _ = await self._create_async(unique_name=unique_name, ttl=ttl) return SyncStreamInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SyncStreamInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, ttl=ttl + ) + instance = SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -477,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, @@ -496,6 +845,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -522,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( @@ -530,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, @@ -554,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, @@ -581,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: """ @@ -596,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: """ @@ -608,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 baca803f95..f7646d1936 100644 --- a/twilio/rest/sync/v1/service/sync_stream/stream_message.py +++ b/twilio/rest/sync/v1/service/sync_stream/stream_message.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -75,13 +76,12 @@ def __init__(self, version: Version, service_sid: str, stream_sid: str): **self._solution ) - def create(self, data: object) -> StreamMessageInstance: + def _create(self, data: object) -> tuple: """ - Create the StreamMessageInstance - - :param data: A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length. + Internal helper for create operation - :returns: The created StreamMessageInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -91,10 +91,23 @@ def create(self, data: object) -> StreamMessageInstance: ) headers = values.of({"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, 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, @@ -102,13 +115,29 @@ def create(self, data: object) -> StreamMessageInstance: stream_sid=self._solution["stream_sid"], ) - async def create_async(self, data: object) -> StreamMessageInstance: + def create_with_http_info(self, data: object) -> ApiResponse: """ - Asynchronously create the StreamMessageInstance + Create the StreamMessageInstance and return response metadata :param data: A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length. - :returns: The created StreamMessageInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(data=data) + instance = StreamMessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, data: object) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -118,10 +147,23 @@ async def create_async(self, data: object) -> StreamMessageInstance: ) headers = values.of({"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, 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, @@ -129,6 +171,23 @@ async def create_async(self, data: object) -> StreamMessageInstance: stream_sid=self._solution["stream_sid"], ) + async def create_with_http_info_async(self, data: object) -> ApiResponse: + """ + Asynchronously create the StreamMessageInstance and return response metadata + + :param data: A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(data=data) + instance = StreamMessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/__init__.py b/twilio/rest/taskrouter/v1/workspace/__init__.py index 60085c1186..5e857c3d0a 100644 --- a/twilio/rest/taskrouter/v1/workspace/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -92,6 +93,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[WorkspaceContext] = None @property @@ -127,6 +129,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WorkspaceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WorkspaceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WorkspaceInstance": """ Fetch the WorkspaceInstance @@ -145,6 +165,24 @@ async def fetch_async(self) -> "WorkspaceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkspaceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkspaceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, default_activity_sid: Union[str, object] = values.unset, @@ -215,6 +253,76 @@ async def update_async( prioritize_queue_order=prioritize_queue_order, ) + def update_with_http_info( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> ApiResponse: + """ + Update the WorkspaceInstance with HTTP info + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + + async def update_with_http_info_async( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkspaceInstance with HTTP info + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + @property def activities(self) -> ActivityList: """ @@ -323,6 +431,20 @@ def __init__(self, version: Version, sid: str): self._real_time_statistics: Optional[WorkspaceRealTimeStatisticsList] = None self._statistics: Optional[WorkspaceStatisticsList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WorkspaceInstance @@ -330,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: @@ -342,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: @@ -354,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: """ @@ -373,19 +567,29 @@ 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( + def _update( self, default_activity_sid: Union[str, object] = values.unset, event_callback_url: Union[str, object] = values.unset, @@ -396,20 +600,14 @@ def update( prioritize_queue_order: Union[ "WorkspaceInstance.QueueOrder", object ] = values.unset, - ) -> WorkspaceInstance: + ) -> tuple: """ - Update the WorkspaceInstance - - :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. - :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). - :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. - :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. - :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). - :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. - :param prioritize_queue_order: + Internal helper for update operation - :returns: The updated WorkspaceInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "DefaultActivitySid": default_activity_sid, @@ -421,16 +619,17 @@ def update( "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" - async def update_async( + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( self, default_activity_sid: Union[str, object] = values.unset, event_callback_url: Union[str, object] = values.unset, @@ -443,7 +642,7 @@ async def update_async( ] = values.unset, ) -> WorkspaceInstance: """ - Asynchronous coroutine to update the WorkspaceInstance + Update the WorkspaceInstance :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). @@ -455,6 +654,73 @@ async def update_async( :returns: The updated WorkspaceInstance """ + payload, _, _ = self._update( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> ApiResponse: + """ + Update the WorkspaceInstance and return response metadata + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + instance = WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "DefaultActivitySid": default_activity_sid, @@ -466,42 +732,116 @@ async def update_async( "PrioritizeQueueOrder": prioritize_queue_order, } ) + 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 WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + headers["Accept"] = "application/json" - @property - def activities(self) -> ActivityList: - """ - Access the activities - """ - if self._activities is None: - self._activities = ActivityList( - self._version, - self._solution["sid"], - ) - return self._activities + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def events(self) -> EventList: - """ - Access the events + async def update_async( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: """ - if self._events is None: - self._events = EventList( - self._version, - self._solution["sid"], - ) - return self._events + Asynchronous coroutine to update the WorkspaceInstance - @property - def tasks(self) -> TaskList: - """ + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: The updated WorkspaceInstance + """ + payload, _, _ = await self._update_async( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_with_http_info_async( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkspaceInstance and return response metadata + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + instance = WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def activities(self) -> ActivityList: + """ + Access the activities + """ + if self._activities is None: + self._activities = ActivityList( + self._version, + self._solution["sid"], + ) + return self._activities + + @property + def events(self) -> EventList: + """ + Access the events + """ + if self._events is None: + self._events = EventList( + self._version, + self._solution["sid"], + ) + return self._events + + @property + def tasks(self) -> TaskList: + """ Access the tasks """ if self._tasks is None: @@ -613,6 +953,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WorkspaceInstance: :param payload: Payload response from the API """ + return WorkspaceInstance(self._version, payload) def __repr__(self) -> str: @@ -637,7 +978,7 @@ def __init__(self, version: Version): self._uri = "/Workspaces" - def create( + def _create( self, friendly_name: str, event_callback_url: Union[str, object] = values.unset, @@ -647,18 +988,12 @@ def create( prioritize_queue_order: Union[ "WorkspaceInstance.QueueOrder", object ] = values.unset, - ) -> WorkspaceInstance: + ) -> tuple: """ - Create the WorkspaceInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. - :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). - :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. - :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). - :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. - :param prioritize_queue_order: - - :returns: The created WorkspaceInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -673,13 +1008,15 @@ def create( ) headers = values.of({"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 WorkspaceInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, event_callback_url: Union[str, object] = values.unset, @@ -691,7 +1028,7 @@ async def create_async( ] = values.unset, ) -> WorkspaceInstance: """ - Asynchronously create the WorkspaceInstance + Create the WorkspaceInstance :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). @@ -702,6 +1039,67 @@ async def create_async( :returns: The created WorkspaceInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + event_callback_url=event_callback_url, + events_filter=events_filter, + multi_task_enabled=multi_task_enabled, + template=template, + prioritize_queue_order=prioritize_queue_order, + ) + return WorkspaceInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> ApiResponse: + """ + Create the WorkspaceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + event_callback_url=event_callback_url, + events_filter=events_filter, + multi_task_enabled=multi_task_enabled, + template=template, + prioritize_queue_order=prioritize_queue_order, + ) + instance = WorkspaceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -715,12 +1113,81 @@ async def create_async( ) headers = values.of({"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, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: + """ + Asynchronously create the WorkspaceInstance + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: The created WorkspaceInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + event_callback_url=event_callback_url, + events_filter=events_filter, + multi_task_enabled=multi_task_enabled, + template=template, + prioritize_queue_order=prioritize_queue_order, + ) return WorkspaceInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WorkspaceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + event_callback_url=event_callback_url, + events_filter=events_filter, + multi_task_enabled=multi_task_enabled, + template=template, + prioritize_queue_order=prioritize_queue_order, + ) + instance = WorkspaceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, friendly_name: Union[str, object] = values.unset, @@ -777,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, @@ -798,6 +1321,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -827,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( @@ -836,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, @@ -863,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( @@ -893,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 e211ef9f72..580948aa5c 100644 --- a/twilio/rest/taskrouter/v1/workspace/activity.py +++ b/twilio/rest/taskrouter/v1/workspace/activity.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[ActivityContext] = None @property @@ -98,6 +100,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ActivityInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ActivityInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ActivityInstance": """ Fetch the ActivityInstance @@ -116,6 +136,24 @@ async def fetch_async(self) -> "ActivityInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ActivityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ActivityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset ) -> "ActivityInstance": @@ -144,6 +182,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the ActivityInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ActivityInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -175,6 +241,20 @@ def __init__(self, version: Version, workspace_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ActivityInstance @@ -182,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: @@ -194,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: @@ -206,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: """ @@ -226,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, @@ -239,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" + + 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 + ) -> 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, @@ -268,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, @@ -297,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 @@ -315,6 +545,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ActivityInstance: :param payload: Payload response from the API """ + return ActivityInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -346,16 +577,14 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/Activities".format(**self._solution) - def create( + def _create( self, friendly_name: str, available: Union[bool, object] = values.unset - ) -> ActivityInstance: + ) -> tuple: """ - Create the ActivityInstance - - :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. - :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. + Internal helper for create operation - :returns: The created ActivityInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -366,24 +595,57 @@ def create( ) headers = values.of({"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, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ActivityInstance: + """ + Create the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. + + :returns: The created ActivityInstance + """ + payload, _, _ = self._create(friendly_name=friendly_name, available=available) return ActivityInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, available: Union[bool, object] = values.unset - ) -> ActivityInstance: + ) -> ApiResponse: """ - Asynchronously create the ActivityInstance + Create the ActivityInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. - :returns: The created ActivityInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, available=available + ) + instance = ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -394,14 +656,51 @@ async def create_async( ) headers = values.of({"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, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ActivityInstance: + """ + Asynchronously create the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. + + :returns: The created ActivityInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, available=available + ) return ActivityInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) + async def create_with_http_info_async( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the ActivityInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, available=available + ) + instance = ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, friendly_name: Union[str, object] = values.unset, @@ -468,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, @@ -491,6 +854,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -523,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( @@ -533,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, @@ -563,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, @@ -596,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: """ @@ -611,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: """ @@ -623,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 534d9cd120..73cc6f2ebf 100644 --- a/twilio/rest/taskrouter/v1/workspace/event.py +++ b/twilio/rest/taskrouter/v1/workspace/event.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -76,6 +77,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[EventContext] = None @property @@ -112,6 +114,24 @@ async def fetch_async(self) -> "EventInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EventInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,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 @@ -148,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: """ @@ -168,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: """ @@ -199,6 +273,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EventInstance: :param payload: Payload response from the API """ + return EventInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -350,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, @@ -391,6 +584,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end_date=end_date, @@ -450,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( @@ -469,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, @@ -526,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, @@ -586,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: """ @@ -601,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: """ @@ -613,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 f71c4bd68f..c03fe1abb9 100644 --- a/twilio/rest/taskrouter/v1/workspace/task/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/task/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,7 +57,7 @@ class Status(object): :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 indicating if a new task should respect a worker's capacity during assignment + :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 """ @@ -114,6 +115,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[TaskContext] = None @property @@ -156,6 +158,34 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo if_match=if_match, ) + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the TaskInstance with HTTP info + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + if_match=if_match, + ) + + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskInstance with HTTP info + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + if_match=if_match, + ) + def fetch(self) -> "TaskInstance": """ Fetch the TaskInstance @@ -174,6 +204,24 @@ async def fetch_async(self) -> "TaskInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TaskInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -193,7 +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. + :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 """ @@ -226,7 +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. + :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 """ @@ -240,6 +288,72 @@ async def update_async( virtual_start_time=virtual_start_time, ) + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Update the TaskInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TaskInstance with HTTP info + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) + @property def reservations(self) -> ReservationList: """ @@ -278,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 @@ -286,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: """ @@ -302,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: @@ -319,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: """ @@ -339,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, @@ -361,20 +581,14 @@ def update( priority: Union[int, object] = values.unset, task_channel: Union[str, object] = values.unset, virtual_start_time: Union[datetime, object] = values.unset, - ) -> TaskInstance: + ) -> tuple: """ - Update the TaskInstance - - :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). - :param attributes: The JSON string that describes the custom attributes of the task. - :param assignment_status: - :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. - :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). - :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future. + Internal helper for update operation - :returns: The updated TaskInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Attributes": attributes, @@ -385,16 +599,53 @@ def update( "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, @@ -402,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, @@ -411,9 +662,9 @@ async def update_async( priority: Union[int, object] = values.unset, task_channel: Union[str, object] = values.unset, virtual_start_time: Union[datetime, object] = values.unset, - ) -> TaskInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the TaskInstance + Update the TaskInstance and return response metadata :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). :param attributes: The JSON string that describes the custom attributes of the task. @@ -421,10 +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. + :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, @@ -435,29 +720,106 @@ async def update_async( "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), } ) - headers = values.of( - { - "If-Match": if_match, - } - ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match - return TaskInstance( - self._version, - payload, - workspace_sid=self._solution["workspace_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 ) - @property - def reservations(self) -> ReservationList: - """ - Access the reservations - """ - if self._reservations is None: + 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: + """ + Access the reservations + """ + if self._reservations is None: self._reservations = ReservationList( self._version, self._solution["workspace_sid"], @@ -483,6 +845,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TaskInstance: :param payload: Payload response from the API """ + return TaskInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -514,7 +877,7 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/Tasks".format(**self._solution) - def create( + def _create( self, timeout: Union[int, object] = values.unset, priority: Union[int, object] = values.unset, @@ -525,21 +888,12 @@ def create( routing_target: Union[str, object] = values.unset, ignore_capacity: Union[str, object] = values.unset, task_queue_sid: Union[str, object] = values.unset, - ) -> TaskInstance: + ) -> tuple: """ - Create the TaskInstance - - :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. - :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). - :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. - :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. - :param attributes: A URL-encoded JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. - :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future. - :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to - :param ignore_capacity: A boolean indicating if a new task should respect a worker's capacity during assignment - :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + Internal helper for create operation - :returns: The created TaskInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -557,15 +911,57 @@ def create( ) headers = values.of({"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, + 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, @@ -576,21 +972,55 @@ async def create_async( routing_target: Union[str, object] = values.unset, ignore_capacity: Union[str, object] = values.unset, task_queue_sid: Union[str, object] = values.unset, - ) -> TaskInstance: + ) -> ApiResponse: """ - Asynchronously create the TaskInstance + Create the TaskInstance and return response metadata :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. - :param attributes: A URL-encoded JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. - :param 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. + :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 indicating if a new task should respect a worker's capacity during assignment + :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( @@ -608,15 +1038,214 @@ async def create_async( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + 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, + timeout: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ignore_capacity: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ) -> TaskInstance: + """ + Asynchronously create the TaskInstance + + :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. + :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. + :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. + :param attributes: A JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + + :returns: The created TaskInstance + """ + payload, _, _ = await self._create_async( + timeout=timeout, + priority=priority, + task_channel=task_channel, + workflow_sid=workflow_sid, + attributes=attributes, + virtual_start_time=virtual_start_time, + routing_target=routing_target, + ignore_capacity=ignore_capacity, + task_queue_sid=task_queue_sid, + ) + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_with_http_info_async( + self, + timeout: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ignore_capacity: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TaskInstance and return response metadata + + :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. + :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. + :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. + :param attributes: A JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + timeout=timeout, + priority=priority, + task_channel=task_channel, + workflow_sid=workflow_sid, + attributes=attributes, + virtual_start_time=virtual_start_time, + routing_target=routing_target, + ignore_capacity=ignore_capacity, + task_queue_sid=task_queue_sid, + ) + instance = TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def stream( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskInstance]: + """ + Streams TaskInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskInstance]: + """ + Asynchronously streams TaskInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + page_size=limits["page_size"], ) - return TaskInstance( - self._version, payload, workspace_sid=self._solution["workspace_sid"] - ) + return self._version.stream_async(page, limits["limit"]) - def stream( + def stream_with_http_info( self, priority: Union[int, object] = values.unset, assignment_status: Union[List[str], object] = values.unset, @@ -630,12 +1259,10 @@ def stream( has_addons: Union[bool, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, - ) -> Iterator[TaskInstance]: + ) -> tuple: """ - Streams TaskInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Streams TaskInstance and returns headers from first page + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. @@ -654,10 +1281,10 @@ def stream( but a limit is defined, stream() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results + :returns: tuple of (generator, status_code, headers) where generator yields instances """ limits = self._version.read_limits(limit, page_size) - page = self.page( + page_response = self.page_with_http_info( priority=priority, assignment_status=assignment_status, workflow_sid=workflow_sid, @@ -671,9 +1298,10 @@ def stream( page_size=limits["page_size"], ) - return self._version.stream(page, limits["limit"]) + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) - async def stream_async( + async def stream_with_http_info_async( self, priority: Union[int, object] = values.unset, assignment_status: Union[List[str], object] = values.unset, @@ -687,12 +1315,10 @@ async def stream_async( has_addons: Union[bool, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, - ) -> AsyncIterator[TaskInstance]: + ) -> tuple: """ - Asynchronously streams TaskInstance records from the API as a generator stream. - This operation lazily loads records as efficiently as possible until the limit - is reached. - The results are returned as a generator, so this operation is memory efficient. + Asynchronously streams TaskInstance and returns headers from first page + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. @@ -711,10 +1337,10 @@ async def stream_async( but a limit is defined, stream() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) - :returns: Generator that will yield up to limit results + :returns: tuple of (generator, status_code, headers) where generator yields instances """ limits = self._version.read_limits(limit, page_size) - page = await self.page_async( + page_response = await self.page_with_http_info_async( priority=priority, assignment_status=assignment_status, workflow_sid=workflow_sid, @@ -728,7 +1354,8 @@ async def stream_async( page_size=limits["page_size"], ) - return self._version.stream_async(page, limits["limit"]) + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) def list( self, @@ -769,6 +1396,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( priority=priority, @@ -825,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( @@ -843,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, @@ -897,8 +1636,14 @@ def page( } ) - 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, @@ -954,10 +1699,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 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: """ @@ -969,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: """ @@ -981,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 50b1ed1273..c6a845b47b 100644 --- a/twilio/rest/taskrouter/v1/workspace/task/reservation.py +++ b/twilio/rest/taskrouter/v1/workspace/task/reservation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -101,6 +102,7 @@ def __init__( "task_sid": task_sid, "sid": sid or self.sid, } + self._context: Optional[ReservationContext] = None @property @@ -138,6 +140,24 @@ async def fetch_async(self) -> "ReservationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ReservationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ReservationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -250,7 +270,7 @@ def update( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. @@ -433,7 +453,7 @@ async def update_async( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. @@ -504,84 +524,7 @@ async def update_async( jitter_buffer_size=jitter_buffer_size, ) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".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, @@ -644,9 +587,9 @@ def update( end_conference_on_customer_exit: Union[bool, object] = values.unset, beep_on_customer_entrance: Union[bool, object] = values.unset, jitter_buffer_size: Union[str, object] = values.unset, - ) -> ReservationInstance: + ) -> ApiResponse: """ - Update the ReservationInstance + Update the ReservationInstance with HTTP info :param if_match: The If-Match HTTP request header :param reservation_status: @@ -693,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. @@ -704,99 +647,67 @@ def update( :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. - :returns: The updated ReservationInstance + :returns: ApiResponse with instance, status code, and headers """ - data = values.of( - { - "ReservationStatus": reservation_status, - "WorkerActivitySid": worker_activity_sid, - "Instruction": instruction, - "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, - "DequeueFrom": dequeue_from, - "DequeueRecord": dequeue_record, - "DequeueTimeout": dequeue_timeout, - "DequeueTo": dequeue_to, - "DequeueStatusCallbackUrl": dequeue_status_callback_url, - "CallFrom": call_from, - "CallRecord": call_record, - "CallTimeout": call_timeout, - "CallTo": call_to, - "CallUrl": call_url, - "CallStatusCallbackUrl": call_status_callback_url, - "CallAccept": serialize.boolean_to_string(call_accept), - "RedirectCallSid": redirect_call_sid, - "RedirectAccept": serialize.boolean_to_string(redirect_accept), - "RedirectUrl": redirect_url, - "To": to, - "From": from_, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "StatusCallbackEvent": serialize.map( - status_callback_event, lambda e: e - ), - "Timeout": timeout, - "Record": serialize.boolean_to_string(record), - "Muted": serialize.boolean_to_string(muted), - "Beep": beep, - "StartConferenceOnEnter": serialize.boolean_to_string( - start_conference_on_enter - ), - "EndConferenceOnExit": serialize.boolean_to_string( - end_conference_on_exit - ), - "WaitUrl": wait_url, - "WaitMethod": wait_method, - "EarlyMedia": serialize.boolean_to_string(early_media), - "MaxParticipants": max_participants, - "ConferenceStatusCallback": conference_status_callback, - "ConferenceStatusCallbackMethod": conference_status_callback_method, - "ConferenceStatusCallbackEvent": serialize.map( - conference_status_callback_event, lambda e: e - ), - "ConferenceRecord": conference_record, - "ConferenceTrim": conference_trim, - "RecordingChannels": recording_channels, - "RecordingStatusCallback": recording_status_callback, - "RecordingStatusCallbackMethod": recording_status_callback_method, - "ConferenceRecordingStatusCallback": conference_recording_status_callback, - "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, - "Region": region, - "SipAuthUsername": sip_auth_username, - "SipAuthPassword": sip_auth_password, - "DequeueStatusCallbackEvent": serialize.map( - dequeue_status_callback_event, lambda e: e - ), - "PostWorkActivitySid": post_work_activity_sid, - "SupervisorMode": supervisor_mode, - "Supervisor": supervisor, - "EndConferenceOnCustomerExit": serialize.boolean_to_string( - end_conference_on_customer_exit - ), - "BeepOnCustomerEntrance": serialize.boolean_to_string( - beep_on_customer_entrance - ), - "JitterBufferSize": jitter_buffer_size, - } - ) - headers = values.of( - { - "If-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, @@ -859,9 +770,9 @@ async def update_async( end_conference_on_customer_exit: Union[bool, object] = values.unset, beep_on_customer_entrance: Union[bool, object] = values.unset, jitter_buffer_size: Union[str, object] = values.unset, - ) -> ReservationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ReservationInstance + Asynchronous coroutine to update the ReservationInstance with HTTP info :param if_match: The If-Match HTTP request header :param reservation_status: @@ -908,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. @@ -919,34 +830,296 @@ async def update_async( :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. - :returns: The updated ReservationInstance + :returns: ApiResponse with instance, status code, and headers """ - data = values.of( - { - "ReservationStatus": reservation_status, - "WorkerActivitySid": worker_activity_sid, - "Instruction": instruction, - "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, - "DequeueFrom": dequeue_from, - "DequeueRecord": dequeue_record, - "DequeueTimeout": dequeue_timeout, - "DequeueTo": dequeue_to, - "DequeueStatusCallbackUrl": dequeue_status_callback_url, - "CallFrom": call_from, - "CallRecord": call_record, - "CallTimeout": call_timeout, - "CallTo": call_to, - "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( + 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, @@ -993,23 +1166,940 @@ async def update_async( "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 self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + payload, _, _ = self._update( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ReservationInstance and return response metadata + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + instance = ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "SupervisorMode": supervisor_mode, + "Supervisor": supervisor, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + payload, _, _ = await self._update_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ReservationInstance and return response metadata + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + 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: """ @@ -1029,6 +2119,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: :param payload: Payload response from the API """ + return ReservationInstance( self._version, payload, @@ -1133,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, @@ -1156,6 +2311,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( reservation_status=reservation_status, @@ -1188,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( @@ -1198,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, @@ -1228,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, @@ -1261,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: """ @@ -1276,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: """ @@ -1288,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 95a7e5efaf..ea27998d19 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_channel.py +++ b/twilio/rest/taskrouter/v1/workspace/task_channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[TaskChannelContext] = None @property @@ -102,6 +104,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TaskChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskChannelInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TaskChannelInstance": """ Fetch the TaskChannelInstance @@ -120,6 +140,24 @@ async def fetch_async(self) -> "TaskChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TaskChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -156,6 +194,42 @@ async def update_async( channel_optimized_routing=channel_optimized_routing, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the TaskChannelInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TaskChannelInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -187,6 +261,20 @@ def __init__(self, version: Version, workspace_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TaskChannelInstance @@ -194,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: @@ -206,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: @@ -218,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: """ @@ -238,32 +399,42 @@ 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 - - :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. - :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + Internal helper for update operation - :returns: The updated TaskChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -272,13 +443,33 @@ def update( ), } ) + 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, + 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, @@ -286,19 +477,43 @@ 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, @@ -307,13 +522,33 @@ 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, + 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, @@ -321,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 @@ -339,6 +599,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TaskChannelInstance: :param payload: Payload response from the API """ + return TaskChannelInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -370,20 +631,17 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/TaskChannels".format(**self._solution) - def create( + def _create( self, friendly_name: str, unique_name: str, channel_optimized_routing: Union[bool, object] = values.unset, - ) -> TaskChannelInstance: + ) -> tuple: """ - Create the TaskChannelInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. - :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. - :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. - - :returns: The created TaskChannelInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -397,28 +655,74 @@ def create( ) headers = values.of({"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, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Create the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The created TaskChannelInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + channel_optimized_routing=channel_optimized_routing, + ) return TaskChannelInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, unique_name: str, channel_optimized_routing: Union[bool, object] = values.unset, - ) -> TaskChannelInstance: + ) -> ApiResponse: """ - Asynchronously create the TaskChannelInstance + Create the TaskChannelInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. - :returns: The created TaskChannelInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + unique_name=unique_name, + channel_optimized_routing=channel_optimized_routing, + ) + instance = TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -432,14 +736,63 @@ async def create_async( ) headers = values.of({"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, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Asynchronously create the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The created TaskChannelInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + channel_optimized_routing=channel_optimized_routing, + ) return TaskChannelInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TaskChannelInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + channel_optimized_routing=channel_optimized_routing, + ) + instance = TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -490,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, @@ -509,6 +912,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -535,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( @@ -543,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, @@ -567,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, @@ -594,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: """ @@ -609,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: """ @@ -621,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 027cf8dbfc..02213bbcc8 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -106,6 +107,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[TaskQueueContext] = None @property @@ -142,6 +144,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TaskQueueInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskQueueInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TaskQueueInstance": """ Fetch the TaskQueueInstance @@ -160,6 +180,24 @@ async def fetch_async(self) -> "TaskQueueInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TaskQueueInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -220,6 +258,66 @@ async def update_async( task_order=task_order, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> ApiResponse: + """ + Update the TaskQueueInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TaskQueueInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) + @property def cumulative_statistics(self) -> TaskQueueCumulativeStatisticsList: """ @@ -276,6 +374,20 @@ def __init__(self, version: Version, workspace_sid: str, sid: str): self._real_time_statistics: Optional[TaskQueueRealTimeStatisticsList] = None self._statistics: Optional[TaskQueueStatisticsList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TaskQueueInstance @@ -283,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: @@ -295,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: @@ -307,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: """ @@ -327,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, @@ -348,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, @@ -371,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, @@ -385,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, @@ -393,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. @@ -404,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, @@ -416,13 +671,45 @@ async def update_async( "TaskOrder": task_order, } ) + 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_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, @@ -430,24 +717,61 @@ async def update_async( sid=self._solution["sid"], ) - @property - def cumulative_statistics(self) -> TaskQueueCumulativeStatisticsList: - """ - Access the cumulative_statistics + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> ApiResponse: """ - if self._cumulative_statistics is None: - self._cumulative_statistics = TaskQueueCumulativeStatisticsList( - self._version, - self._solution["workspace_sid"], - self._solution["sid"], - ) - return self._cumulative_statistics + Asynchronous coroutine to update the TaskQueueInstance and return response metadata - @property - def real_time_statistics(self) -> TaskQueueRealTimeStatisticsList: - """ - Access the real_time_statistics - """ + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) + instance = TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def cumulative_statistics(self) -> TaskQueueCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + if self._cumulative_statistics is None: + self._cumulative_statistics = TaskQueueCumulativeStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._cumulative_statistics + + @property + def real_time_statistics(self) -> TaskQueueRealTimeStatisticsList: + """ + Access the real_time_statistics + """ if self._real_time_statistics is None: self._real_time_statistics = TaskQueueRealTimeStatisticsList( self._version, @@ -487,6 +811,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TaskQueueInstance: :param payload: Payload response from the API """ + return TaskQueueInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -523,7 +848,7 @@ def __init__(self, version: Version, workspace_sid: str): ] = None self._statistics: Optional[TaskQueuesStatisticsList] = None - def create( + def _create( self, friendly_name: str, target_workers: Union[str, object] = values.unset, @@ -531,18 +856,12 @@ def create( task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, reservation_activity_sid: Union[str, object] = values.unset, assignment_activity_sid: Union[str, object] = values.unset, - ) -> TaskQueueInstance: + ) -> tuple: """ - Create the TaskQueueInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. - :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). - :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. - :param task_order: - :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. - :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. - - :returns: The created TaskQueueInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -557,15 +876,48 @@ def create( ) headers = values.of({"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, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> TaskQueueInstance: + """ + Create the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). + :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :param task_order: + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. + + :returns: The created TaskQueueInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + target_workers=target_workers, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + ) return TaskQueueInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, target_workers: Union[str, object] = values.unset, @@ -573,9 +925,9 @@ async def create_async( task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, reservation_activity_sid: Union[str, object] = values.unset, assignment_activity_sid: Union[str, object] = values.unset, - ) -> TaskQueueInstance: + ) -> ApiResponse: """ - Asynchronously create the TaskQueueInstance + Create the TaskQueueInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). @@ -584,7 +936,35 @@ async def create_async( :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. - :returns: The created TaskQueueInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + target_workers=target_workers, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + ) + instance = TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -599,14 +979,81 @@ async def create_async( ) headers = values.of({"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, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> TaskQueueInstance: + """ + Asynchronously create the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). + :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :param task_order: + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. + + :returns: The created TaskQueueInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + target_workers=target_workers, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + ) return TaskQueueInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TaskQueueInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). + :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :param task_order: + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + target_workers=target_workers, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + ) + instance = TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, friendly_name: Union[str, object] = values.unset, @@ -685,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, @@ -712,6 +1235,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -750,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( @@ -762,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, @@ -798,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, @@ -837,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, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["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 + ) ) - return TaskQueuePage(self._version, response, self._solution) + 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: """ @@ -852,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: """ @@ -864,7 +1567,7 @@ async def get_page_async(self, target_url: str) -> TaskQueuePage: :returns: Page of TaskQueueInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return TaskQueuePage(self._version, response, self._solution) + return TaskQueuePage(self._version, response, solution=self._solution) @property def bulk_real_time_statistics(self) -> TaskQueueBulkRealTimeStatisticsList: diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py index 9ccef45773..5273d75dea 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -80,6 +81,25 @@ def __init__(self, version: Version, workspace_sid: str): **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: @@ -90,17 +110,44 @@ def create( :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" - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers - ) + headers["Accept"] = "application/json" - return TaskQueueBulkRealTimeStatisticsInstance( - self._version, payload, workspace_sid=self._solution["workspace_sid"] + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers ) async def create_async( @@ -113,18 +160,26 @@ async def create_async( :returns: The created TaskQueueBulkRealTimeStatisticsInstance """ - data = body.to_dict() + payload, _, _ = await self._create_async(body=body) + return TaskQueueBulkRealTimeStatisticsInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - headers["Content-Type"] = "application/json" + async def create_with_http_info_async( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the TaskQueueBulkRealTimeStatisticsInstance and return response metadata - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + :param body: - return TaskQueueBulkRealTimeStatisticsInstance( + :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: """ 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 acb8b79a29..5741772450 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -119,6 +120,7 @@ def __init__( "workspace_sid": workspace_sid, "task_queue_sid": task_queue_sid, } + self._context: Optional[TaskQueueCumulativeStatisticsContext] = None @property @@ -191,6 +193,60 @@ async def fetch_async( split_by_wait_time=split_by_wait_time, ) + def fetch_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the TaskQueueCumulativeStatisticsInstance with HTTP info + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance with HTTP info + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -224,27 +280,22 @@ def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): **self._solution ) - def fetch( + def _fetch( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> TaskQueueCumulativeStatisticsInstance: + ) -> tuple: """ - Fetch the TaskQueueCumulativeStatisticsInstance - - :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + Internal helper for fetch operation - :returns: The fetched TaskQueueCumulativeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -254,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, @@ -263,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. @@ -280,10 +363,39 @@ async def fetch_async( :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. - :returns: The fetched TaskQueueCumulativeStatisticsInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -293,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, @@ -304,6 +446,40 @@ async def fetch_async( task_queue_sid=self._solution["task_queue_sid"], ) + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance and return response metadata + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py index faca804702..94dc68cbbc 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,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. @@ -86,6 +87,7 @@ def __init__( "workspace_sid": workspace_sid, "task_queue_sid": task_queue_sid, } + self._context: Optional[TaskQueueRealTimeStatisticsContext] = None @property @@ -132,6 +134,34 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the TaskQueueRealTimeStatisticsInstance with HTTP info + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance with HTTP info + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -165,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 - - :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`. + Internal helper for fetch operation - :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, @@ -191,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) + + 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 = 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, @@ -219,6 +296,27 @@ async def fetch_async( task_queue_sid=self._solution["task_queue_sid"], ) + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance and return response metadata + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + task_channel=task_channel + ) + instance = TaskQueueRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py index 2a09f62a68..444f3925a7 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( "workspace_sid": workspace_sid, "task_queue_sid": task_queue_sid, } + self._context: Optional[TaskQueueStatisticsContext] = None @property @@ -123,6 +125,60 @@ async def fetch_async( split_by_wait_time=split_by_wait_time, ) + def fetch_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the TaskQueueStatisticsInstance with HTTP info + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance with HTTP info + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,27 +212,22 @@ def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): ) ) - def fetch( + def _fetch( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> TaskQueueStatisticsInstance: + ) -> tuple: """ - Fetch the TaskQueueStatisticsInstance - - :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + Internal helper for fetch operation - :returns: The fetched TaskQueueStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -186,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, @@ -195,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. @@ -212,10 +295,39 @@ async def fetch_async( :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. - :returns: The fetched TaskQueueStatisticsInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = TaskQueueStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -225,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, @@ -236,6 +378,40 @@ async def fetch_async( task_queue_sid=self._solution["task_queue_sid"], ) + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance and return response metadata + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = TaskQueueStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py index bec2d81b40..aa6fb95b0f 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TaskQueuesStatisticsInstance: :param payload: Payload response from the API """ + return TaskQueuesStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -185,6 +187,94 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TaskQueuesStatisticsInstance and returns headers from first page + + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TaskQueuesStatisticsInstance and returns headers from first page + + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, end_date: Union[datetime, object] = values.unset, @@ -216,6 +306,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end_date=end_date, @@ -260,6 +351,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -274,6 +366,92 @@ async def list_async( ) ] + def list_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TaskQueuesStatisticsInstance and returns headers from first page + + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TaskQueuesStatisticsInstance and returns headers from first page + + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, end_date: Union[datetime, object] = values.unset, @@ -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 + ) + 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, + } ) - return TaskQueuesStatisticsPage(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 = 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 8f6ff4c7e1..1295d3716e 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -86,6 +87,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[WorkerContext] = None @property @@ -128,6 +130,34 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo if_match=if_match, ) + def delete_with_http_info( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Deletes the WorkerInstance with HTTP info + + :param if_match: The If-Match HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info( + if_match=if_match, + ) + + async def delete_with_http_info_async( + self, if_match: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WorkerInstance with HTTP info + + :param if_match: The If-Match HTTP request header + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async( + if_match=if_match, + ) + def fetch(self) -> "WorkerInstance": """ Fetch the WorkerInstance @@ -146,6 +176,24 @@ async def fetch_async(self) -> "WorkerInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkerInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkerInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -200,6 +248,60 @@ async def update_async( reject_pending_reservations=reject_pending_reservations, ) + def update_with_http_info( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the WorkerInstance with HTTP info + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) + + async def update_with_http_info_async( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkerInstance with HTTP info + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) + @property def reservations(self) -> ReservationList: """ @@ -254,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 @@ -262,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: """ @@ -278,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: @@ -295,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: """ @@ -315,38 +512,45 @@ 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, @@ -357,16 +561,47 @@ def update( ), } ) - 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" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> WorkerInstance: + """ + Update the WorkerInstance + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: The updated WorkerInstance + """ + payload, _, _ = self._update( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) return WorkerInstance( self._version, payload, @@ -374,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. @@ -391,8 +626,38 @@ 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, @@ -403,16 +668,47 @@ async def update_async( ), } ) - 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 ) + 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, @@ -420,8 +716,42 @@ async def update_async( sid=self._solution["sid"], ) - @property - def reservations(self) -> ReservationList: + 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 """ @@ -477,6 +807,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WorkerInstance: :param payload: Payload response from the API """ + return WorkerInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -512,20 +843,17 @@ def __init__(self, version: Version, workspace_sid: str): self._real_time_statistics: Optional[WorkersRealTimeStatisticsList] = None self._statistics: Optional[WorkersStatisticsList] = None - def create( + def _create( self, friendly_name: str, activity_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> WorkerInstance: + ) -> tuple: """ - Create the WorkerInstance - - :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 {}. + Internal helper for create operation - :returns: The created WorkerInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -537,28 +865,74 @@ def create( ) headers = values.of({"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, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> WorkerInstance: + """ + Create the WorkerInstance + + :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. + :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. + :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + + :returns: The created WorkerInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + activity_sid=activity_sid, + attributes=attributes, + ) return WorkerInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, activity_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> WorkerInstance: + ) -> ApiResponse: """ - Asynchronously create the WorkerInstance + Create the WorkerInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. - :returns: The created WorkerInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + activity_sid=activity_sid, + attributes=attributes, + ) + instance = WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -570,14 +944,63 @@ async def create_async( ) headers = values.of({"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, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> WorkerInstance: + """ + Asynchronously create the WorkerInstance + + :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. + :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. + :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + + :returns: The created WorkerInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + activity_sid=activity_sid, + attributes=attributes, + ) return WorkerInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WorkerInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. + :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. + :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + activity_sid=activity_sid, + attributes=attributes, + ) + instance = WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, activity_name: Union[str, object] = values.unset, @@ -680,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, @@ -715,6 +1238,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( activity_name=activity_name, @@ -765,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( @@ -781,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, @@ -829,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, @@ -880,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: """ @@ -895,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: """ @@ -907,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 b7dc4bca9e..227b2b83d7 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/reservation.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/reservation.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -96,6 +97,7 @@ def __init__( "worker_sid": worker_sid, "sid": sid or self.sid, } + self._context: Optional[ReservationContext] = None @property @@ -133,6 +135,24 @@ async def fetch_async(self) -> "ReservationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ReservationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ReservationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, if_match: Union[str, object] = values.unset, @@ -241,7 +261,7 @@ def update( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. @@ -416,7 +436,7 @@ async def update_async( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. @@ -483,82 +503,7 @@ async def update_async( jitter_buffer_size=jitter_buffer_size, ) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".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, @@ -617,9 +562,9 @@ def update( end_conference_on_customer_exit: Union[bool, object] = values.unset, beep_on_customer_entrance: Union[bool, object] = values.unset, jitter_buffer_size: Union[str, object] = values.unset, - ) -> ReservationInstance: + ) -> ApiResponse: """ - Update the ReservationInstance + Update the ReservationInstance with HTTP info :param if_match: The If-Match HTTP request header :param reservation_status: @@ -666,7 +611,7 @@ def update( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. @@ -675,97 +620,65 @@ def update( :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. - :returns: The updated ReservationInstance + :returns: ApiResponse with instance, status code, and headers """ - data = values.of( - { - "ReservationStatus": reservation_status, - "WorkerActivitySid": worker_activity_sid, - "Instruction": instruction, - "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, - "DequeueFrom": dequeue_from, - "DequeueRecord": dequeue_record, - "DequeueTimeout": dequeue_timeout, - "DequeueTo": dequeue_to, - "DequeueStatusCallbackUrl": dequeue_status_callback_url, - "CallFrom": call_from, - "CallRecord": call_record, - "CallTimeout": call_timeout, - "CallTo": call_to, - "CallUrl": call_url, - "CallStatusCallbackUrl": call_status_callback_url, - "CallAccept": serialize.boolean_to_string(call_accept), - "RedirectCallSid": redirect_call_sid, - "RedirectAccept": serialize.boolean_to_string(redirect_accept), - "RedirectUrl": redirect_url, - "To": to, - "From": from_, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "StatusCallbackEvent": serialize.map( - status_callback_event, lambda e: e - ), - "Timeout": timeout, - "Record": serialize.boolean_to_string(record), - "Muted": serialize.boolean_to_string(muted), - "Beep": beep, - "StartConferenceOnEnter": serialize.boolean_to_string( - start_conference_on_enter - ), - "EndConferenceOnExit": serialize.boolean_to_string( - end_conference_on_exit - ), - "WaitUrl": wait_url, - "WaitMethod": wait_method, - "EarlyMedia": serialize.boolean_to_string(early_media), - "MaxParticipants": max_participants, - "ConferenceStatusCallback": conference_status_callback, - "ConferenceStatusCallbackMethod": conference_status_callback_method, - "ConferenceStatusCallbackEvent": serialize.map( - conference_status_callback_event, lambda e: e - ), - "ConferenceRecord": conference_record, - "ConferenceTrim": conference_trim, - "RecordingChannels": recording_channels, - "RecordingStatusCallback": recording_status_callback, - "RecordingStatusCallbackMethod": recording_status_callback_method, - "ConferenceRecordingStatusCallback": conference_recording_status_callback, - "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, - "Region": region, - "SipAuthUsername": sip_auth_username, - "SipAuthPassword": sip_auth_password, - "DequeueStatusCallbackEvent": serialize.map( - dequeue_status_callback_event, lambda e: e - ), - "PostWorkActivitySid": post_work_activity_sid, - "EndConferenceOnCustomerExit": serialize.boolean_to_string( - end_conference_on_customer_exit - ), - "BeepOnCustomerEntrance": serialize.boolean_to_string( - beep_on_customer_entrance - ), - "JitterBufferSize": jitter_buffer_size, - } - ) - headers = values.of( - { - "If-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, @@ -824,9 +737,9 @@ async def update_async( end_conference_on_customer_exit: Union[bool, object] = values.unset, beep_on_customer_entrance: Union[bool, object] = values.unset, jitter_buffer_size: Union[str, object] = values.unset, - ) -> ReservationInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the ReservationInstance + Asynchronous coroutine to update the ReservationInstance with HTTP info :param if_match: The If-Match HTTP request header :param reservation_status: @@ -873,7 +786,7 @@ async def update_async( :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. - :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. :param sip_auth_username: The SIP username used for authentication. :param sip_auth_password: The SIP password for authentication. :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. @@ -882,40 +795,811 @@ async def update_async( :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. - :returns: The updated ReservationInstance + :returns: ApiResponse with instance, status code, and headers """ - data = values.of( - { - "ReservationStatus": reservation_status, - "WorkerActivitySid": worker_activity_sid, - "Instruction": instruction, - "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, - "DequeueFrom": dequeue_from, - "DequeueRecord": dequeue_record, - "DequeueTimeout": dequeue_timeout, - "DequeueTo": dequeue_to, - "DequeueStatusCallbackUrl": dequeue_status_callback_url, - "CallFrom": call_from, - "CallRecord": call_record, - "CallTimeout": call_timeout, - "CallTo": call_to, - "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, + 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 ), @@ -954,23 +1638,385 @@ async def update_async( "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"], + ) + + 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 - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + :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: """ @@ -990,6 +2036,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: :param payload: Payload response from the API """ + return ReservationInstance( self._version, payload, @@ -1088,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, @@ -1109,6 +2212,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( reservation_status=reservation_status, @@ -1138,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( @@ -1147,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, @@ -1174,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, @@ -1204,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: """ @@ -1219,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: """ @@ -1231,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 f48ebb3a62..61d407fd38 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -80,6 +81,7 @@ def __init__( "worker_sid": worker_sid, "sid": sid or self.sid, } + self._context: Optional[WorkerChannelContext] = None @property @@ -117,6 +119,24 @@ async def fetch_async(self) -> "WorkerChannelInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkerChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkerChannelInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, capacity: Union[int, object] = values.unset, @@ -153,6 +173,42 @@ async def update_async( available=available, ) + def update_with_http_info( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the WorkerChannelInstance with HTTP info + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + capacity=capacity, + available=available, + ) + + async def update_with_http_info_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkerChannelInstance with HTTP info + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + capacity=capacity, + available=available, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -188,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 @@ -195,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: """ @@ -216,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 - - :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. - :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + Internal helper for update operation - :returns: The updated WorkerChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Capacity": capacity, "Available": serialize.boolean_to_string(available), } ) + 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, + 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, @@ -264,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": serialize.boolean_to_string(available), } ) + 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, + 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, @@ -298,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 @@ -316,6 +510,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WorkerChannelInstance: :param payload: Payload response from the API """ + return WorkerChannelInstance( self._version, payload, @@ -404,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, @@ -423,6 +668,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -449,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( @@ -457,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, @@ -481,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, @@ -508,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: """ @@ -523,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: """ @@ -535,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 61618d2961..f2fbcd5c34 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -49,6 +50,7 @@ def __init__( "workspace_sid": workspace_sid, "worker_sid": worker_sid, } + self._context: Optional[WorkerStatisticsContext] = None @property @@ -115,6 +117,54 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkerStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkerStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -148,25 +198,21 @@ def __init__(self, version: Version, workspace_sid: str, worker_sid: str): ) ) - def fetch( + def _fetch( self, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, end_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, - ) -> WorkerStatisticsInstance: + ) -> tuple: """ - Fetch the WorkerStatisticsInstance - - :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + Internal helper for fetch operation - :returns: The fetched WorkerStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -175,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, @@ -184,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) + + 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 - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -211,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, @@ -222,6 +351,37 @@ async def fetch_async( worker_sid=self._solution["worker_sid"], ) + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkerStatisticsInstance and return response metadata + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + instance = WorkerStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py index b18e7f123b..dbcce53c8c 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -74,6 +75,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str self._solution = { "workspace_sid": workspace_sid, } + self._context: Optional[WorkersCumulativeStatisticsContext] = None @property @@ -139,6 +141,54 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkersCumulativeStatisticsInstance with HTTP info + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance with HTTP info + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -170,25 +220,21 @@ def __init__(self, version: Version, workspace_sid: str): **self._solution ) - def fetch( + def _fetch( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, - ) -> WorkersCumulativeStatisticsInstance: + ) -> tuple: """ - Fetch the WorkersCumulativeStatisticsInstance - - :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, @@ -197,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) + + async def _fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> tuple: """ + Internal async helper for fetch operation - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -232,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 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 277889ae7a..9efc95193a 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -45,6 +46,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str self._solution = { "workspace_sid": workspace_sid, } + self._context: Optional[WorkersRealTimeStatisticsContext] = None @property @@ -90,6 +92,34 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the WorkersRealTimeStatisticsInstance with HTTP info + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance with HTTP info + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -121,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: @@ -131,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`. - data = values.of( + :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 + + 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( @@ -156,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: """ diff --git a/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py index 0cd09ec124..8a3a21b6bb 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -42,6 +43,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str self._solution = { "workspace_sid": workspace_sid, } + self._context: Optional[WorkersStatisticsContext] = None @property @@ -125,6 +127,72 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkersStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + friendly_name=friendly_name, + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkersStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + friendly_name=friendly_name, + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -154,7 +222,7 @@ def __init__(self, version: Version, workspace_sid: str): **self._solution ) - def fetch( + def _fetch( self, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, @@ -163,22 +231,15 @@ def fetch( task_queue_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, task_channel: Union[str, object] = values.unset, - ) -> WorkersStatisticsInstance: + ) -> tuple: """ - Fetch the WorkersStatisticsInstance + Internal helper for fetch operation - :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. - :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. - :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. - :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - - :returns: The fetched WorkersStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -190,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, @@ -207,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. @@ -219,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) - 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_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 + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -234,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 diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py b/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py index 96d7aabf0e..547db90579 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -85,6 +86,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[WorkflowContext] = None @property @@ -121,6 +123,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WorkflowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WorkflowInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WorkflowInstance": """ Fetch the WorkflowInstance @@ -139,6 +159,24 @@ async def fetch_async(self) -> "WorkflowInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkflowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -199,6 +237,66 @@ async def update_async( re_evaluate_tasks=re_evaluate_tasks, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the WorkflowInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WorkflowInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) + @property def cumulative_statistics(self) -> WorkflowCumulativeStatisticsList: """ @@ -255,6 +353,20 @@ def __init__(self, version: Version, workspace_sid: str, sid: str): self._real_time_statistics: Optional[WorkflowRealTimeStatisticsList] = None self._statistics: Optional[WorkflowStatisticsList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WorkflowInstance @@ -262,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: @@ -274,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: @@ -286,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: """ @@ -306,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, @@ -327,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, @@ -350,13 +541,45 @@ def update( "ReEvaluateTasks": re_evaluate_tasks, } ) + 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, + 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, @@ -364,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, @@ -372,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. @@ -383,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, @@ -395,13 +650,45 @@ async def update_async( "ReEvaluateTasks": re_evaluate_tasks, } ) + 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, + 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, @@ -409,24 +696,61 @@ 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( self._version, @@ -466,6 +790,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WorkflowInstance: :param payload: Payload response from the API """ + return WorkflowInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -497,24 +822,19 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/Workflows".format(**self._solution) - def create( + def _create( self, friendly_name: str, configuration: str, assignment_callback_url: Union[str, object] = values.unset, fallback_assignment_callback_url: Union[str, object] = values.unset, task_reservation_timeout: Union[int, object] = values.unset, - ) -> WorkflowInstance: + ) -> tuple: """ - Create the WorkflowInstance + Internal helper for create operation - :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. - :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. - :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. - :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. - :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. - - :returns: The created WorkflowInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -528,24 +848,54 @@ def create( ) headers = values.of({"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, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> WorkflowInstance: + """ + Create the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + + :returns: The created WorkflowInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + configuration=configuration, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + task_reservation_timeout=task_reservation_timeout, + ) return WorkflowInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, configuration: str, assignment_callback_url: Union[str, object] = values.unset, fallback_assignment_callback_url: Union[str, object] = values.unset, task_reservation_timeout: Union[int, object] = values.unset, - ) -> WorkflowInstance: + ) -> ApiResponse: """ - Asynchronously create the WorkflowInstance + Create the WorkflowInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. @@ -553,7 +903,33 @@ async def create_async( :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. - :returns: The created WorkflowInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + configuration=configuration, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + task_reservation_timeout=task_reservation_timeout, + ) + instance = WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -567,14 +943,75 @@ async def create_async( ) headers = values.of({"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, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> WorkflowInstance: + """ + Asynchronously create the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + + :returns: The created WorkflowInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + configuration=configuration, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + task_reservation_timeout=task_reservation_timeout, + ) return WorkflowInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WorkflowInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + configuration=configuration, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + task_reservation_timeout=task_reservation_timeout, + ) + instance = WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, friendly_name: Union[str, object] = values.unset, @@ -631,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, @@ -652,6 +1145,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -681,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( @@ -690,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, @@ -717,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, @@ -747,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: """ @@ -762,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: """ @@ -774,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 e06cab0114..f104fd41bb 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -119,6 +120,7 @@ def __init__( "workspace_sid": workspace_sid, "workflow_sid": workflow_sid, } + self._context: Optional[WorkflowCumulativeStatisticsContext] = None @property @@ -191,6 +193,60 @@ async def fetch_async( split_by_wait_time=split_by_wait_time, ) + def fetch_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkflowCumulativeStatisticsInstance with HTTP info + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance with HTTP info + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -224,27 +280,22 @@ def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): **self._solution ) - def fetch( + def _fetch( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> WorkflowCumulativeStatisticsInstance: + ) -> tuple: """ - Fetch the WorkflowCumulativeStatisticsInstance - - :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + Internal helper for fetch operation - :returns: The fetched WorkflowCumulativeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -254,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, @@ -263,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. @@ -280,10 +363,39 @@ async def fetch_async( :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. - :returns: The fetched WorkflowCumulativeStatisticsInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkflowCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -293,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, @@ -304,6 +446,40 @@ async def fetch_async( workflow_sid=self._solution["workflow_sid"], ) + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance and return response metadata + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkflowCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py index 415d4223e4..944dac550d 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "workspace_sid": workspace_sid, "workflow_sid": workflow_sid, } + self._context: Optional[WorkflowRealTimeStatisticsContext] = None @property @@ -112,6 +114,34 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the WorkflowRealTimeStatisticsInstance with HTTP info + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance with HTTP info + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -145,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 - - :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`. + Internal helper for fetch operation - :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, @@ -171,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) + + 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 = 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, @@ -199,6 +276,27 @@ async def fetch_async( workflow_sid=self._solution["workflow_sid"], ) + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance and return response metadata + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + task_channel=task_channel + ) + instance = WorkflowRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py index f86590e40f..1aa812c61d 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( "workspace_sid": workspace_sid, "workflow_sid": workflow_sid, } + self._context: Optional[WorkflowStatisticsContext] = None @property @@ -123,6 +125,60 @@ async def fetch_async( split_by_wait_time=split_by_wait_time, ) + def fetch_with_http_info( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkflowStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,27 +212,22 @@ def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): ) ) - def fetch( + def _fetch( self, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, end_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> WorkflowStatisticsInstance: + ) -> tuple: """ - Fetch the WorkflowStatisticsInstance - - :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + Internal helper for fetch operation - :returns: The fetched WorkflowStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -186,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, @@ -195,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. @@ -212,10 +295,39 @@ async def fetch_async( :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. - :returns: The fetched WorkflowStatisticsInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkflowStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - data = values.of( + async def _fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -225,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, @@ -236,6 +378,40 @@ async def fetch_async( workflow_sid=self._solution["workflow_sid"], ) + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkflowStatisticsInstance and return response metadata + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + instance = WorkflowStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py index 2b223641ae..8d7262cdb0 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -110,6 +111,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str self._solution = { "workspace_sid": workspace_sid, } + self._context: Optional[WorkspaceCumulativeStatisticsContext] = None @property @@ -181,6 +183,60 @@ async def fetch_async( split_by_wait_time=split_by_wait_time, ) + def fetch_with_http_info( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkspaceCumulativeStatisticsInstance with HTTP info + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_with_http_info_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance with HTTP info + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -212,27 +268,22 @@ def __init__(self, version: Version, workspace_sid: str): **self._solution ) - def fetch( + def _fetch( self, end_date: Union[datetime, object] = values.unset, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> WorkspaceCumulativeStatisticsInstance: + ) -> tuple: """ - Fetch the WorkspaceCumulativeStatisticsInstance - - :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + Internal helper for fetch operation - :returns: The fetched WorkspaceCumulativeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -242,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. @@ -267,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) + + 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, @@ -280,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 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 35b50c0b21..559ec20f14 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -65,6 +66,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str self._solution = { "workspace_sid": workspace_sid, } + self._context: Optional[WorkspaceRealTimeStatisticsContext] = None @property @@ -110,6 +112,34 @@ async def fetch_async( task_channel=task_channel, ) + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the WorkspaceRealTimeStatisticsInstance with HTTP info + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + task_channel=task_channel, + ) + + async def fetch_with_http_info_async( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance with HTTP info + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + task_channel=task_channel, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,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: @@ -151,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`. - data = values.of( + :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 + + 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( @@ -176,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: """ diff --git a/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py b/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py index 19eb885675..e30fecf3e1 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -42,6 +43,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str self._solution = { "workspace_sid": workspace_sid, } + self._context: Optional[WorkspaceStatisticsContext] = None @property @@ -113,6 +115,60 @@ async def fetch_async( split_by_wait_time=split_by_wait_time, ) + def fetch_with_http_info( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the WorkspaceStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_with_http_info_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance with HTTP info + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -140,27 +196,22 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/Statistics".format(**self._solution) - def fetch( + def _fetch( self, minutes: Union[int, object] = values.unset, start_date: Union[datetime, object] = values.unset, end_date: Union[datetime, object] = values.unset, task_channel: Union[str, object] = values.unset, split_by_wait_time: Union[str, object] = values.unset, - ) -> WorkspaceStatisticsInstance: + ) -> tuple: """ - Fetch the WorkspaceStatisticsInstance - - :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. - :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. - :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. - :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. - :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + Internal helper for fetch operation - :returns: The fetched WorkspaceStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -170,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. @@ -195,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) + + 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), @@ -208,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 diff --git a/twilio/rest/trunking/v1/trunk/__init__.py b/twilio/rest/trunking/v1/trunk/__init__.py index b1bfdba117..7697c323b6 100644 --- a/twilio/rest/trunking/v1/trunk/__init__.py +++ b/twilio/rest/trunking/v1/trunk/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -50,6 +51,7 @@ class TransferSetting(object): :ivar transfer_caller_id: :ivar cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. :ivar auth_type: The types of authentication mapped to the domain. Can be: `IP_ACL` and `CREDENTIAL_LIST`. If both are mapped, the values are returned in a comma delimited list. If empty, the domain will not receive any traffic. + :ivar symmetric_rtp_enabled: Whether Symmetric RTP is enabled for the trunk. When Symmetric RTP is disabled, Twilio will send RTP to the destination negotiated in the SDP. Disabling Symmetric RTP is considered to be more secure and therefore recommended. See [Symmetric RTP](https://www.twilio.com/docs/sip-trunking#symmetric-rtp) for more information. :ivar auth_type_set: Reserved. :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. @@ -80,6 +82,9 @@ def __init__( ) self.cnam_lookup_enabled: Optional[bool] = payload.get("cnam_lookup_enabled") self.auth_type: Optional[str] = payload.get("auth_type") + self.symmetric_rtp_enabled: Optional[bool] = payload.get( + "symmetric_rtp_enabled" + ) self.auth_type_set: Optional[List[str]] = payload.get("auth_type_set") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") @@ -94,6 +99,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[TrunkContext] = None @property @@ -129,6 +135,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrunkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrunkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TrunkInstance": """ Fetch the TrunkInstance @@ -147,6 +171,24 @@ async def fetch_async(self) -> "TrunkInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -223,6 +265,82 @@ async def update_async( transfer_caller_id=transfer_caller_id, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> ApiResponse: + """ + Update the TrunkInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrunkInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + @property def credentials_lists(self) -> CredentialListList: """ @@ -291,6 +409,20 @@ def __init__(self, version: Version, sid: str): self._phone_numbers: Optional[PhoneNumberList] = None self._recordings: Optional[RecordingList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TrunkInstance @@ -298,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: @@ -310,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: @@ -322,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: """ @@ -341,19 +545,29 @@ 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( + def _update( self, friendly_name: Union[str, object] = values.unset, domain_name: Union[str, object] = values.unset, @@ -365,21 +579,14 @@ def update( transfer_caller_id: Union[ "TrunkInstance.TransferCallerId", object ] = values.unset, - ) -> TrunkInstance: + ) -> tuple: """ - Update the TrunkInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. - :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. - :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. - :param transfer_mode: - :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. - :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. - :param transfer_caller_id: + Internal helper for update operation - :returns: The updated TrunkInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -392,16 +599,17 @@ def update( "TransferCallerId": transfer_caller_id, } ) + 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, 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, domain_name: Union[str, object] = values.unset, @@ -415,7 +623,7 @@ async def update_async( ] = values.unset, ) -> TrunkInstance: """ - Asynchronous coroutine to update the TrunkInstance + Update the TrunkInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. @@ -428,6 +636,78 @@ async def update_async( :returns: The updated TrunkInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + return TrunkInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> ApiResponse: + """ + Update the TrunkInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + instance = TrunkInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "FriendlyName": friendly_name, @@ -440,40 +720,120 @@ async def update_async( "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 @@ -527,6 +887,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TrunkInstance: :param payload: Payload response from the API """ + return TrunkInstance(self._version, payload) def __repr__(self) -> str: @@ -551,7 +912,7 @@ def __init__(self, version: Version): self._uri = "/Trunks" - def create( + def _create( self, friendly_name: Union[str, object] = values.unset, domain_name: Union[str, object] = values.unset, @@ -563,20 +924,12 @@ def create( transfer_caller_id: Union[ "TrunkInstance.TransferCallerId", object ] = values.unset, - ) -> TrunkInstance: + ) -> tuple: """ - Create the TrunkInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. - :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. - :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. - :param transfer_mode: - :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. - :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. - :param transfer_caller_id: + Internal helper for create operation - :returns: The created TrunkInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -593,13 +946,15 @@ def create( ) headers = values.of({"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 TrunkInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: Union[str, object] = values.unset, domain_name: Union[str, object] = values.unset, @@ -613,7 +968,7 @@ async def create_async( ] = values.unset, ) -> TrunkInstance: """ - Asynchronously create the TrunkInstance + Create the TrunkInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. @@ -626,6 +981,77 @@ async def create_async( :returns: The created TrunkInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + return TrunkInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> ApiResponse: + """ + Create the TrunkInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + instance = TrunkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -641,12 +1067,93 @@ async def create_async( ) headers = values.of({"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, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: + """ + Asynchronously create the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The created TrunkInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) return TrunkInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the TrunkInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + instance = TrunkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -697,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, @@ -716,6 +1273,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -742,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( @@ -750,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, @@ -774,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( @@ -801,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 e04bb30720..540c501396 100644 --- a/twilio/rest/trunking/v1/trunk/credential_list.py +++ b/twilio/rest/trunking/v1/trunk/credential_list.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,6 +59,7 @@ def __init__( "trunk_sid": trunk_sid, "sid": sid or self.sid, } + self._context: Optional[CredentialListContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CredentialListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CredentialListInstance": """ Fetch the CredentialListInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "CredentialListInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CredentialListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,6 +179,20 @@ def __init__(self, version: Version, trunk_sid: str, sid: str): } self._uri = "/Trunks/{trunk_sid}/CredentialLists/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CredentialListInstance @@ -148,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: @@ -160,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: @@ -172,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: """ @@ -192,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: """ @@ -223,6 +359,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: :param payload: Payload response from the API """ + return CredentialListInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) @@ -254,13 +391,12 @@ def __init__(self, version: Version, trunk_sid: str): } self._uri = "/Trunks/{trunk_sid}/CredentialLists".format(**self._solution) - def create(self, credential_list_sid: str) -> CredentialListInstance: + def _create(self, credential_list_sid: str) -> tuple: """ - Create the CredentialListInstance + 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( @@ -270,21 +406,49 @@ def create(self, credential_list_sid: str) -> CredentialListInstance: ) headers = values.of({"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, 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( @@ -294,14 +458,47 @@ async def create_async(self, credential_list_sid: str) -> CredentialListInstance ) headers = values.of({"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, 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, @@ -352,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, @@ -371,6 +618,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -397,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( @@ -405,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, @@ -429,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, @@ -456,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: """ @@ -471,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: """ @@ -483,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 957084cb62..49c56e5cbc 100644 --- a/twilio/rest/trunking/v1/trunk/ip_access_control_list.py +++ b/twilio/rest/trunking/v1/trunk/ip_access_control_list.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,6 +59,7 @@ def __init__( "trunk_sid": trunk_sid, "sid": sid or self.sid, } + self._context: Optional[IpAccessControlListContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "IpAccessControlListInstance": """ Fetch the IpAccessControlListInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "IpAccessControlListInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -143,6 +181,20 @@ def __init__(self, version: Version, trunk_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the IpAccessControlListInstance @@ -150,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: @@ -162,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: @@ -174,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: """ @@ -194,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: """ @@ -225,6 +361,7 @@ def get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: :param payload: Payload response from the API """ + return IpAccessControlListInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) @@ -256,13 +393,12 @@ def __init__(self, version: Version, trunk_sid: str): } self._uri = "/Trunks/{trunk_sid}/IpAccessControlLists".format(**self._solution) - def create(self, ip_access_control_list_sid: str) -> IpAccessControlListInstance: + def _create(self, ip_access_control_list_sid: str) -> tuple: """ - Create the IpAccessControlListInstance - - :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + Internal helper for create operation - :returns: The created IpAccessControlListInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -272,23 +408,51 @@ def create(self, ip_access_control_list_sid: str) -> IpAccessControlListInstance ) headers = values.of({"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, ip_access_control_list_sid: str) -> IpAccessControlListInstance: + """ + Create the IpAccessControlListInstance + + :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + + :returns: The created IpAccessControlListInstance + """ + payload, _, _ = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) return IpAccessControlListInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) - async def create_async( - self, ip_access_control_list_sid: str - ) -> IpAccessControlListInstance: + def create_with_http_info(self, ip_access_control_list_sid: str) -> ApiResponse: """ - Asynchronously create the IpAccessControlListInstance + Create the IpAccessControlListInstance and return response metadata :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. - :returns: The created IpAccessControlListInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ip_access_control_list_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -298,14 +462,49 @@ async def create_async( ) headers = values.of({"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, ip_access_control_list_sid: str + ) -> IpAccessControlListInstance: + """ + Asynchronously create the IpAccessControlListInstance + + :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + + :returns: The created IpAccessControlListInstance + """ + payload, _, _ = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) return IpAccessControlListInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) + async def create_with_http_info_async( + self, ip_access_control_list_sid: str + ) -> ApiResponse: + """ + Asynchronously create the IpAccessControlListInstance and return response metadata + + :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid + ) + instance = IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -356,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, @@ -375,6 +624,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -401,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( @@ -409,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, @@ -433,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, @@ -460,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: """ @@ -475,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: """ @@ -487,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 e8e77180e8..4ac87498f8 100644 --- a/twilio/rest/trunking/v1/trunk/origination_url.py +++ b/twilio/rest/trunking/v1/trunk/origination_url.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "trunk_sid": trunk_sid, "sid": sid or self.sid, } + self._context: Optional[OriginationUrlContext] = None @property @@ -102,6 +104,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the OriginationUrlInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OriginationUrlInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "OriginationUrlInstance": """ Fetch the OriginationUrlInstance @@ -120,6 +140,24 @@ async def fetch_async(self) -> "OriginationUrlInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OriginationUrlInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the OriginationUrlInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, weight: Union[int, object] = values.unset, @@ -174,6 +212,60 @@ async def update_async( sip_url=sip_url, ) + def update_with_http_info( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the OriginationUrlInstance with HTTP info + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + + async def update_with_http_info_async( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the OriginationUrlInstance with HTTP info + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -203,6 +295,20 @@ def __init__(self, version: Version, trunk_sid: str, sid: str): } self._uri = "/Trunks/{trunk_sid}/OriginationUrls/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the OriginationUrlInstance @@ -210,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: @@ -222,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: @@ -234,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: """ @@ -254,38 +433,45 @@ 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, @@ -295,13 +481,42 @@ def update( "SipUrl": sip_url, } ) + 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, + 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, @@ -309,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. @@ -326,8 +541,38 @@ 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, @@ -337,13 +582,42 @@ async def update_async( "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, @@ -351,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 @@ -369,6 +677,7 @@ def get_instance(self, payload: Dict[str, Any]) -> OriginationUrlInstance: :param payload: Payload response from the API """ + return OriginationUrlInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) @@ -400,24 +709,19 @@ def __init__(self, version: Version, trunk_sid: str): } self._uri = "/Trunks/{trunk_sid}/OriginationUrls".format(**self._solution) - def create( + def _create( self, weight: int, priority: int, enabled: bool, friendly_name: str, sip_url: str, - ) -> OriginationUrlInstance: + ) -> tuple: """ - Create the OriginationUrlInstance - - :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. - :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. - :param enabled: Whether the URL is enabled. The default is `true`. - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. - :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + Internal helper for create operation - :returns: The created OriginationUrlInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -431,24 +735,54 @@ def create( ) headers = values.of({"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, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> OriginationUrlInstance: + """ + Create the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + + :returns: The created OriginationUrlInstance + """ + payload, _, _ = self._create( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) return OriginationUrlInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) - async def create_async( + def create_with_http_info( self, weight: int, priority: int, enabled: bool, friendly_name: str, sip_url: str, - ) -> OriginationUrlInstance: + ) -> ApiResponse: """ - Asynchronously create the OriginationUrlInstance + Create the OriginationUrlInstance and return response metadata :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. @@ -456,7 +790,33 @@ async def create_async( :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. - :returns: The created OriginationUrlInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + instance = OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -470,14 +830,75 @@ async def create_async( ) headers = values.of({"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, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> OriginationUrlInstance: + """ + Asynchronously create the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + + :returns: The created OriginationUrlInstance + """ + payload, _, _ = await self._create_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) return OriginationUrlInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) + async def create_with_http_info_async( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> ApiResponse: + """ + Asynchronously create the OriginationUrlInstance and return response metadata + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + instance = OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -528,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, @@ -547,6 +1018,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -573,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( @@ -581,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, @@ -605,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, @@ -632,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: """ @@ -647,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: """ @@ -659,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 75cb5f6c64..20abc377fb 100644 --- a/twilio/rest/trunking/v1/trunk/phone_number.py +++ b/twilio/rest/trunking/v1/trunk/phone_number.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -35,7 +36,7 @@ class AddressRequirement(object): :ivar address_requirements: :ivar api_version: The API version used to start a new TwiML session. :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. - :ivar capabilities: The set of Boolean properties that indicate whether a phone number can receive calls or messages. Capabilities are `Voice`, `SMS`, and `MMS` and each capability can be: `true` or `false`. + :ivar capabilities: :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar friendly_name: The string that you assigned to describe the resource. @@ -74,7 +75,7 @@ def __init__( ] = payload.get("address_requirements") self.api_version: Optional[str] = payload.get("api_version") self.beta: Optional[bool] = payload.get("beta") - self.capabilities: Optional[Dict[str, object]] = payload.get("capabilities") + self.capabilities: Optional[str] = payload.get("capabilities") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -109,6 +110,7 @@ def __init__( "trunk_sid": trunk_sid, "sid": sid or self.sid, } + self._context: Optional[PhoneNumberContext] = None @property @@ -145,6 +147,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "PhoneNumberInstance": """ Fetch the PhoneNumberInstance @@ -163,6 +183,24 @@ async def fetch_async(self) -> "PhoneNumberInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -192,6 +230,20 @@ def __init__(self, version: Version, trunk_sid: str, sid: str): } self._uri = "/Trunks/{trunk_sid}/PhoneNumbers/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the PhoneNumberInstance @@ -199,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: @@ -211,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: @@ -223,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: """ @@ -243,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: """ @@ -274,6 +410,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: :param payload: Payload response from the API """ + return PhoneNumberInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) @@ -305,13 +442,12 @@ def __init__(self, version: Version, trunk_sid: str): } self._uri = "/Trunks/{trunk_sid}/PhoneNumbers".format(**self._solution) - def create(self, phone_number_sid: str) -> PhoneNumberInstance: + def _create(self, phone_number_sid: str) -> tuple: """ - Create the PhoneNumberInstance - - :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( @@ -321,21 +457,47 @@ def create(self, phone_number_sid: str) -> PhoneNumberInstance: ) headers = values.of({"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, 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( @@ -345,14 +507,43 @@ async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: ) headers = values.of({"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, 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, @@ -403,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, @@ -422,6 +663,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -448,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( @@ -456,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, @@ -480,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, @@ -507,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: """ @@ -522,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: """ @@ -534,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 1a431b496b..5e29ae8205 100644 --- a/twilio/rest/trunking/v1/trunk/recording.py +++ b/twilio/rest/trunking/v1/trunk/recording.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -47,6 +48,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], trunk_sid: str): self._solution = { "trunk_sid": trunk_sid, } + self._context: Optional[RecordingContext] = None @property @@ -82,6 +84,24 @@ async def fetch_async(self) -> "RecordingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, mode: Union["RecordingInstance.RecordingMode", object] = values.unset, @@ -118,6 +138,42 @@ async def update_async( trim=trim, ) + def update_with_http_info( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> ApiResponse: + """ + Update the RecordingInstance with HTTP info + + :param mode: + :param trim: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + mode=mode, + trim=trim, + ) + + async def update_with_http_info_async( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RecordingInstance with HTTP info + + :param mode: + :param trim: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + mode=mode, + trim=trim, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -145,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 @@ -152,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: """ @@ -171,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, @@ -196,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( @@ -226,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: """ diff --git a/twilio/rest/trusthub/v1/compliance_inquiries.py b/twilio/rest/trusthub/v1/compliance_inquiries.py index 6fe6c297bd..107749eaa4 100644 --- a/twilio/rest/trusthub/v1/compliance_inquiries.py +++ b/twilio/rest/trusthub/v1/compliance_inquiries.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( self._solution = { "customer_id": customer_id or self.customer_id, } + self._context: Optional[ComplianceInquiriesContext] = None @property @@ -61,30 +63,68 @@ def _proxy(self) -> "ComplianceInquiriesContext": ) return self._context - def update(self, primary_profile_sid: str) -> "ComplianceInquiriesInstance": + 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 + 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: @@ -116,56 +156,132 @@ def __init__(self, version: Version, customer_id: str): **self._solution ) - def update(self, primary_profile_sid: str) -> ComplianceInquiriesInstance: + def _update( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> tuple: """ - 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. + Internal helper for update operation - :returns: The updated ComplianceInquiriesInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "PrimaryProfileSid": primary_profile_sid, + "ThemeSetId": theme_set_id, } ) + 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, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ComplianceInquiriesInstance: + """ + Update the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceInquiriesInstance + """ + payload, _, _ = self._update( + primary_profile_sid=primary_profile_sid, theme_set_id=theme_set_id + ) return ComplianceInquiriesInstance( self._version, payload, customer_id=self._solution["customer_id"] ) - async def update_async( - self, primary_profile_sid: str - ) -> ComplianceInquiriesInstance: + def update_with_http_info( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ApiResponse: """ - Asynchronous coroutine to update the ComplianceInquiriesInstance + Update the ComplianceInquiriesInstance and return response metadata :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. - :returns: The updated ComplianceInquiriesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + primary_profile_sid=primary_profile_sid, theme_set_id=theme_set_id + ) + instance = ComplianceInquiriesInstance( + self._version, payload, customer_id=self._solution["customer_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> tuple: """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "PrimaryProfileSid": primary_profile_sid, + "ThemeSetId": theme_set_id, } ) + 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, 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 @@ -189,62 +305,156 @@ def __init__(self, version: Version): self._uri = "/ComplianceInquiries/Customers/Initialize" - def create( + def _create( self, - primary_profile_sid: str, notification_email: Union[str, object] = values.unset, - ) -> ComplianceInquiriesInstance: + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> tuple: """ - Create the ComplianceInquiriesInstance + Internal helper for create operation - :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. - :param 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. - - :returns: The created ComplianceInquiriesInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( { - "PrimaryProfileSid": primary_profile_sid, "NotificationEmail": notification_email, + "ThemeSetId": theme_set_id, + "PrimaryProfileSid": primary_profile_sid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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 ComplianceInquiriesInstance(self._version, payload) - - async def create_async( + def create( self, - primary_profile_sid: str, notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, ) -> ComplianceInquiriesInstance: """ - Asynchronously create the ComplianceInquiriesInstance + Create the ComplianceInquiriesInstance - :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. :param notification_email: The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. + :param theme_set_id: Theme id for styling the inquiry form. + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. :returns: The created ComplianceInquiriesInstance """ + payload, _, _ = self._create( + notification_email=notification_email, + theme_set_id=theme_set_id, + primary_profile_sid=primary_profile_sid, + ) + return ComplianceInquiriesInstance(self._version, payload) + + def create_with_http_info( + self, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ComplianceInquiriesInstance and return response metadata + + :param notification_email: The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. + :param theme_set_id: Theme id for styling the inquiry form. + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + notification_email=notification_email, + theme_set_id=theme_set_id, + primary_profile_sid=primary_profile_sid, + ) + instance = ComplianceInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { - "PrimaryProfileSid": primary_profile_sid, "NotificationEmail": notification_email, + "ThemeSetId": theme_set_id, + "PrimaryProfileSid": primary_profile_sid, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> ComplianceInquiriesInstance: + """ + Asynchronously create the ComplianceInquiriesInstance + + :param notification_email: The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. + :param theme_set_id: Theme id for styling the inquiry form. + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + + :returns: The created ComplianceInquiriesInstance + """ + payload, _, _ = await self._create_async( + notification_email=notification_email, + theme_set_id=theme_set_id, + primary_profile_sid=primary_profile_sid, + ) return ComplianceInquiriesInstance(self._version, payload) + async def create_with_http_info_async( + self, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ComplianceInquiriesInstance and return response metadata + + :param notification_email: The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. + :param theme_set_id: Theme id for styling the inquiry form. + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + notification_email=notification_email, + theme_set_id=theme_set_id, + primary_profile_sid=primary_profile_sid, + ) + instance = ComplianceInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, customer_id: str) -> ComplianceInquiriesContext: """ Constructs a ComplianceInquiriesContext diff --git a/twilio/rest/trusthub/v1/compliance_registration_inquiries.py b/twilio/rest/trusthub/v1/compliance_registration_inquiries.py index 2f6c465341..5c5a96de06 100644 --- a/twilio/rest/trusthub/v1/compliance_registration_inquiries.py +++ b/twilio/rest/trusthub/v1/compliance_registration_inquiries.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( self._solution = { "registration_id": registration_id or self.registration_id, } + self._context: Optional[ComplianceRegistrationInquiriesContext] = None @property @@ -120,6 +122,42 @@ async def update_async( theme_set_id=theme_set_id, ) + def update_with_http_info( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ComplianceRegistrationInquiriesInstance with HTTP info + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + is_isv_embed=is_isv_embed, + theme_set_id=theme_set_id, + ) + + async def update_with_http_info_async( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ComplianceRegistrationInquiriesInstance with HTTP info + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + is_isv_embed=is_isv_embed, + theme_set_id=theme_set_id, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -151,6 +189,34 @@ def __init__(self, version: Version, registration_id: str): **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, @@ -164,21 +230,60 @@ def update( :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({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ComplianceRegistrationInquiriesInstance( - self._version, payload, registration_id=self._solution["registration_id"] + 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( @@ -194,22 +299,33 @@ async def update_async( :returns: The updated ComplianceRegistrationInquiriesInstance """ - data = values.of( - { - "IsIsvEmbed": serialize.boolean_to_string(is_isv_embed), - "ThemeSetId": theme_set_id, - } + payload, _, _ = await self._update_async( + is_isv_embed=is_isv_embed, theme_set_id=theme_set_id ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + return ComplianceRegistrationInquiriesInstance( + self._version, payload, registration_id=self._solution["registration_id"] ) - return ComplianceRegistrationInquiriesInstance( + 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: """ @@ -238,7 +354,7 @@ def __init__(self, version: Version): "/ComplianceInquiries/Registration/RegulatoryCompliance/GB/Initialize" ) - def create( + def _create( self, end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", @@ -284,51 +400,12 @@ def create( isv_registering_for_self_or_tenant: Union[str, object] = values.unset, status_callback_url: Union[str, object] = values.unset, theme_set_id: Union[str, object] = values.unset, - ) -> ComplianceRegistrationInquiriesInstance: + ) -> tuple: """ - Create the ComplianceRegistrationInquiriesInstance + Internal helper for create operation - :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 + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -380,13 +457,15 @@ def create( ) headers = values.of({"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 ComplianceRegistrationInquiriesInstance(self._version, payload) - - async def create_async( + def create( self, end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", @@ -434,7 +513,7 @@ async def create_async( theme_set_id: Union[str, object] = values.unset, ) -> ComplianceRegistrationInquiriesInstance: """ - Asynchronously create the ComplianceRegistrationInquiriesInstance + Create the ComplianceRegistrationInquiriesInstance :param end_user_type: :param phone_number_type: @@ -478,6 +557,238 @@ async def create_async( :returns: The created ComplianceRegistrationInquiriesInstance """ + payload, _, _ = self._create( + end_user_type=end_user_type, + phone_number_type=phone_number_type, + business_identity_type=business_identity_type, + business_registration_authority=business_registration_authority, + business_legal_name=business_legal_name, + notification_email=notification_email, + accepted_notification_receipt=accepted_notification_receipt, + business_registration_number=business_registration_number, + business_website_url=business_website_url, + friendly_name=friendly_name, + authorized_representative1_first_name=authorized_representative1_first_name, + authorized_representative1_last_name=authorized_representative1_last_name, + authorized_representative1_phone=authorized_representative1_phone, + authorized_representative1_email=authorized_representative1_email, + authorized_representative1_date_of_birth=authorized_representative1_date_of_birth, + address_street=address_street, + address_street_secondary=address_street_secondary, + address_city=address_city, + address_subdivision=address_subdivision, + address_postal_code=address_postal_code, + address_country_code=address_country_code, + emergency_address_street=emergency_address_street, + emergency_address_street_secondary=emergency_address_street_secondary, + emergency_address_city=emergency_address_city, + emergency_address_subdivision=emergency_address_subdivision, + emergency_address_postal_code=emergency_address_postal_code, + emergency_address_country_code=emergency_address_country_code, + use_address_as_emergency_address=use_address_as_emergency_address, + file_name=file_name, + file=file, + first_name=first_name, + last_name=last_name, + date_of_birth=date_of_birth, + individual_email=individual_email, + individual_phone=individual_phone, + is_isv_embed=is_isv_embed, + isv_registering_for_self_or_tenant=isv_registering_for_self_or_tenant, + status_callback_url=status_callback_url, + theme_set_id=theme_set_id, + ) + return ComplianceRegistrationInquiriesInstance(self._version, payload) + + def create_with_http_info( + self, + end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", + phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", + business_identity_type: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessIdentityType", object + ] = values.unset, + business_registration_authority: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessRegistrationAuthority", + object, + ] = values.unset, + business_legal_name: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + accepted_notification_receipt: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_website_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + authorized_representative1_first_name: Union[str, object] = values.unset, + authorized_representative1_last_name: Union[str, object] = values.unset, + authorized_representative1_phone: Union[str, object] = values.unset, + authorized_representative1_email: Union[str, object] = values.unset, + authorized_representative1_date_of_birth: Union[str, object] = values.unset, + address_street: Union[str, object] = values.unset, + address_street_secondary: Union[str, object] = values.unset, + address_city: Union[str, object] = values.unset, + address_subdivision: Union[str, object] = values.unset, + address_postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + emergency_address_street: Union[str, object] = values.unset, + emergency_address_street_secondary: Union[str, object] = values.unset, + emergency_address_city: Union[str, object] = values.unset, + emergency_address_subdivision: Union[str, object] = values.unset, + emergency_address_postal_code: Union[str, object] = values.unset, + emergency_address_country_code: Union[str, object] = values.unset, + use_address_as_emergency_address: Union[bool, object] = values.unset, + file_name: Union[str, object] = values.unset, + file: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + individual_email: Union[str, object] = values.unset, + individual_phone: Union[str, object] = values.unset, + is_isv_embed: Union[bool, object] = values.unset, + isv_registering_for_self_or_tenant: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ComplianceRegistrationInquiriesInstance and return response metadata + + :param end_user_type: + :param phone_number_type: + :param business_identity_type: + :param business_registration_authority: + :param business_legal_name: he name of the business or organization using the Tollfree number. + :param notification_email: he email address to receive the notification about the verification result. + :param accepted_notification_receipt: The email address to receive the notification about the verification result. + :param business_registration_number: Business registration number of the business + :param business_website_url: The URL of the business website + :param friendly_name: Friendly name for your business information + :param authorized_representative1_first_name: First name of the authorized representative + :param authorized_representative1_last_name: Last name of the authorized representative + :param authorized_representative1_phone: Phone number of the authorized representative + :param authorized_representative1_email: Email address of the authorized representative + :param authorized_representative1_date_of_birth: Birthdate of the authorized representative + :param address_street: Street address of the business + :param address_street_secondary: Street address of the business + :param address_city: City of the business + :param address_subdivision: State or province of the business + :param address_postal_code: Postal code of the business + :param address_country_code: Country code of the business + :param emergency_address_street: Street address of the business + :param emergency_address_street_secondary: Street address of the business + :param emergency_address_city: City of the business + :param emergency_address_subdivision: State or province of the business + :param emergency_address_postal_code: Postal code of the business + :param emergency_address_country_code: Country code of the business + :param use_address_as_emergency_address: Use the business address as the emergency address + :param file_name: The name of the verification document to upload + :param file: The verification document to upload + :param first_name: The first name of the Individual User. + :param last_name: The last name of the Individual User. + :param date_of_birth: The date of birth of the Individual User. + :param individual_email: The email address of the Individual User. + :param individual_phone: The phone number of the Individual User. + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param isv_registering_for_self_or_tenant: Indicates if the isv registering for self or tenant. + :param status_callback_url: The url we call to inform you of bundle changes. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + end_user_type=end_user_type, + phone_number_type=phone_number_type, + business_identity_type=business_identity_type, + business_registration_authority=business_registration_authority, + business_legal_name=business_legal_name, + notification_email=notification_email, + accepted_notification_receipt=accepted_notification_receipt, + business_registration_number=business_registration_number, + business_website_url=business_website_url, + friendly_name=friendly_name, + authorized_representative1_first_name=authorized_representative1_first_name, + authorized_representative1_last_name=authorized_representative1_last_name, + authorized_representative1_phone=authorized_representative1_phone, + authorized_representative1_email=authorized_representative1_email, + authorized_representative1_date_of_birth=authorized_representative1_date_of_birth, + address_street=address_street, + address_street_secondary=address_street_secondary, + address_city=address_city, + address_subdivision=address_subdivision, + address_postal_code=address_postal_code, + address_country_code=address_country_code, + emergency_address_street=emergency_address_street, + emergency_address_street_secondary=emergency_address_street_secondary, + emergency_address_city=emergency_address_city, + emergency_address_subdivision=emergency_address_subdivision, + emergency_address_postal_code=emergency_address_postal_code, + emergency_address_country_code=emergency_address_country_code, + use_address_as_emergency_address=use_address_as_emergency_address, + file_name=file_name, + file=file, + first_name=first_name, + last_name=last_name, + date_of_birth=date_of_birth, + individual_email=individual_email, + individual_phone=individual_phone, + is_isv_embed=is_isv_embed, + isv_registering_for_self_or_tenant=isv_registering_for_self_or_tenant, + status_callback_url=status_callback_url, + theme_set_id=theme_set_id, + ) + instance = ComplianceRegistrationInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", + phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", + business_identity_type: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessIdentityType", object + ] = values.unset, + business_registration_authority: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessRegistrationAuthority", + object, + ] = values.unset, + business_legal_name: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + accepted_notification_receipt: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_website_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + authorized_representative1_first_name: Union[str, object] = values.unset, + authorized_representative1_last_name: Union[str, object] = values.unset, + authorized_representative1_phone: Union[str, object] = values.unset, + authorized_representative1_email: Union[str, object] = values.unset, + authorized_representative1_date_of_birth: Union[str, object] = values.unset, + address_street: Union[str, object] = values.unset, + address_street_secondary: Union[str, object] = values.unset, + address_city: Union[str, object] = values.unset, + address_subdivision: Union[str, object] = values.unset, + address_postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + emergency_address_street: Union[str, object] = values.unset, + emergency_address_street_secondary: Union[str, object] = values.unset, + emergency_address_city: Union[str, object] = values.unset, + emergency_address_subdivision: Union[str, object] = values.unset, + emergency_address_postal_code: Union[str, object] = values.unset, + emergency_address_country_code: Union[str, object] = values.unset, + use_address_as_emergency_address: Union[bool, object] = values.unset, + file_name: Union[str, object] = values.unset, + file: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + individual_email: Union[str, object] = values.unset, + individual_phone: Union[str, object] = values.unset, + is_isv_embed: Union[bool, object] = values.unset, + isv_registering_for_self_or_tenant: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -528,12 +839,285 @@ async def create_async( ) headers = values.of({"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, + end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", + phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", + business_identity_type: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessIdentityType", object + ] = values.unset, + business_registration_authority: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessRegistrationAuthority", + object, + ] = values.unset, + business_legal_name: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + accepted_notification_receipt: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_website_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + authorized_representative1_first_name: Union[str, object] = values.unset, + authorized_representative1_last_name: Union[str, object] = values.unset, + authorized_representative1_phone: Union[str, object] = values.unset, + authorized_representative1_email: Union[str, object] = values.unset, + authorized_representative1_date_of_birth: Union[str, object] = values.unset, + address_street: Union[str, object] = values.unset, + address_street_secondary: Union[str, object] = values.unset, + address_city: Union[str, object] = values.unset, + address_subdivision: Union[str, object] = values.unset, + address_postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + emergency_address_street: Union[str, object] = values.unset, + emergency_address_street_secondary: Union[str, object] = values.unset, + emergency_address_city: Union[str, object] = values.unset, + emergency_address_subdivision: Union[str, object] = values.unset, + emergency_address_postal_code: Union[str, object] = values.unset, + emergency_address_country_code: Union[str, object] = values.unset, + use_address_as_emergency_address: Union[bool, object] = values.unset, + file_name: Union[str, object] = values.unset, + file: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + individual_email: Union[str, object] = values.unset, + individual_phone: Union[str, object] = values.unset, + is_isv_embed: Union[bool, object] = values.unset, + isv_registering_for_self_or_tenant: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceRegistrationInquiriesInstance: + """ + Asynchronously create the ComplianceRegistrationInquiriesInstance + + :param end_user_type: + :param phone_number_type: + :param business_identity_type: + :param business_registration_authority: + :param business_legal_name: he name of the business or organization using the Tollfree number. + :param notification_email: he email address to receive the notification about the verification result. + :param accepted_notification_receipt: The email address to receive the notification about the verification result. + :param business_registration_number: Business registration number of the business + :param business_website_url: The URL of the business website + :param friendly_name: Friendly name for your business information + :param authorized_representative1_first_name: First name of the authorized representative + :param authorized_representative1_last_name: Last name of the authorized representative + :param authorized_representative1_phone: Phone number of the authorized representative + :param authorized_representative1_email: Email address of the authorized representative + :param authorized_representative1_date_of_birth: Birthdate of the authorized representative + :param address_street: Street address of the business + :param address_street_secondary: Street address of the business + :param address_city: City of the business + :param address_subdivision: State or province of the business + :param address_postal_code: Postal code of the business + :param address_country_code: Country code of the business + :param emergency_address_street: Street address of the business + :param emergency_address_street_secondary: Street address of the business + :param emergency_address_city: City of the business + :param emergency_address_subdivision: State or province of the business + :param emergency_address_postal_code: Postal code of the business + :param emergency_address_country_code: Country code of the business + :param use_address_as_emergency_address: Use the business address as the emergency address + :param file_name: The name of the verification document to upload + :param file: The verification document to upload + :param first_name: The first name of the Individual User. + :param last_name: The last name of the Individual User. + :param date_of_birth: The date of birth of the Individual User. + :param individual_email: The email address of the Individual User. + :param individual_phone: The phone number of the Individual User. + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param isv_registering_for_self_or_tenant: Indicates if the isv registering for self or tenant. + :param status_callback_url: The url we call to inform you of bundle changes. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The created ComplianceRegistrationInquiriesInstance + """ + payload, _, _ = await self._create_async( + end_user_type=end_user_type, + phone_number_type=phone_number_type, + business_identity_type=business_identity_type, + business_registration_authority=business_registration_authority, + business_legal_name=business_legal_name, + notification_email=notification_email, + accepted_notification_receipt=accepted_notification_receipt, + business_registration_number=business_registration_number, + business_website_url=business_website_url, + friendly_name=friendly_name, + authorized_representative1_first_name=authorized_representative1_first_name, + authorized_representative1_last_name=authorized_representative1_last_name, + authorized_representative1_phone=authorized_representative1_phone, + authorized_representative1_email=authorized_representative1_email, + authorized_representative1_date_of_birth=authorized_representative1_date_of_birth, + address_street=address_street, + address_street_secondary=address_street_secondary, + address_city=address_city, + address_subdivision=address_subdivision, + address_postal_code=address_postal_code, + address_country_code=address_country_code, + emergency_address_street=emergency_address_street, + emergency_address_street_secondary=emergency_address_street_secondary, + emergency_address_city=emergency_address_city, + emergency_address_subdivision=emergency_address_subdivision, + emergency_address_postal_code=emergency_address_postal_code, + emergency_address_country_code=emergency_address_country_code, + use_address_as_emergency_address=use_address_as_emergency_address, + file_name=file_name, + file=file, + first_name=first_name, + last_name=last_name, + date_of_birth=date_of_birth, + individual_email=individual_email, + individual_phone=individual_phone, + is_isv_embed=is_isv_embed, + isv_registering_for_self_or_tenant=isv_registering_for_self_or_tenant, + status_callback_url=status_callback_url, + theme_set_id=theme_set_id, + ) return ComplianceRegistrationInquiriesInstance(self._version, payload) + async def create_with_http_info_async( + self, + end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", + phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", + business_identity_type: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessIdentityType", object + ] = values.unset, + business_registration_authority: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessRegistrationAuthority", + object, + ] = values.unset, + business_legal_name: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + accepted_notification_receipt: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_website_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + authorized_representative1_first_name: Union[str, object] = values.unset, + authorized_representative1_last_name: Union[str, object] = values.unset, + authorized_representative1_phone: Union[str, object] = values.unset, + authorized_representative1_email: Union[str, object] = values.unset, + authorized_representative1_date_of_birth: Union[str, object] = values.unset, + address_street: Union[str, object] = values.unset, + address_street_secondary: Union[str, object] = values.unset, + address_city: Union[str, object] = values.unset, + address_subdivision: Union[str, object] = values.unset, + address_postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + emergency_address_street: Union[str, object] = values.unset, + emergency_address_street_secondary: Union[str, object] = values.unset, + emergency_address_city: Union[str, object] = values.unset, + emergency_address_subdivision: Union[str, object] = values.unset, + emergency_address_postal_code: Union[str, object] = values.unset, + emergency_address_country_code: Union[str, object] = values.unset, + use_address_as_emergency_address: Union[bool, object] = values.unset, + file_name: Union[str, object] = values.unset, + file: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + individual_email: Union[str, object] = values.unset, + individual_phone: Union[str, object] = values.unset, + is_isv_embed: Union[bool, object] = values.unset, + isv_registering_for_self_or_tenant: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ComplianceRegistrationInquiriesInstance and return response metadata + + :param end_user_type: + :param phone_number_type: + :param business_identity_type: + :param business_registration_authority: + :param business_legal_name: he name of the business or organization using the Tollfree number. + :param notification_email: he email address to receive the notification about the verification result. + :param accepted_notification_receipt: The email address to receive the notification about the verification result. + :param business_registration_number: Business registration number of the business + :param business_website_url: The URL of the business website + :param friendly_name: Friendly name for your business information + :param authorized_representative1_first_name: First name of the authorized representative + :param authorized_representative1_last_name: Last name of the authorized representative + :param authorized_representative1_phone: Phone number of the authorized representative + :param authorized_representative1_email: Email address of the authorized representative + :param authorized_representative1_date_of_birth: Birthdate of the authorized representative + :param address_street: Street address of the business + :param address_street_secondary: Street address of the business + :param address_city: City of the business + :param address_subdivision: State or province of the business + :param address_postal_code: Postal code of the business + :param address_country_code: Country code of the business + :param emergency_address_street: Street address of the business + :param emergency_address_street_secondary: Street address of the business + :param emergency_address_city: City of the business + :param emergency_address_subdivision: State or province of the business + :param emergency_address_postal_code: Postal code of the business + :param emergency_address_country_code: Country code of the business + :param use_address_as_emergency_address: Use the business address as the emergency address + :param file_name: The name of the verification document to upload + :param file: The verification document to upload + :param first_name: The first name of the Individual User. + :param last_name: The last name of the Individual User. + :param date_of_birth: The date of birth of the Individual User. + :param individual_email: The email address of the Individual User. + :param individual_phone: The phone number of the Individual User. + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param isv_registering_for_self_or_tenant: Indicates if the isv registering for self or tenant. + :param status_callback_url: The url we call to inform you of bundle changes. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + end_user_type=end_user_type, + phone_number_type=phone_number_type, + business_identity_type=business_identity_type, + business_registration_authority=business_registration_authority, + business_legal_name=business_legal_name, + notification_email=notification_email, + accepted_notification_receipt=accepted_notification_receipt, + business_registration_number=business_registration_number, + business_website_url=business_website_url, + friendly_name=friendly_name, + authorized_representative1_first_name=authorized_representative1_first_name, + authorized_representative1_last_name=authorized_representative1_last_name, + authorized_representative1_phone=authorized_representative1_phone, + authorized_representative1_email=authorized_representative1_email, + authorized_representative1_date_of_birth=authorized_representative1_date_of_birth, + address_street=address_street, + address_street_secondary=address_street_secondary, + address_city=address_city, + address_subdivision=address_subdivision, + address_postal_code=address_postal_code, + address_country_code=address_country_code, + emergency_address_street=emergency_address_street, + emergency_address_street_secondary=emergency_address_street_secondary, + emergency_address_city=emergency_address_city, + emergency_address_subdivision=emergency_address_subdivision, + emergency_address_postal_code=emergency_address_postal_code, + emergency_address_country_code=emergency_address_country_code, + use_address_as_emergency_address=use_address_as_emergency_address, + file_name=file_name, + file=file, + first_name=first_name, + last_name=last_name, + date_of_birth=date_of_birth, + individual_email=individual_email, + individual_phone=individual_phone, + is_isv_embed=is_isv_embed, + isv_registering_for_self_or_tenant=isv_registering_for_self_or_tenant, + status_callback_url=status_callback_url, + theme_set_id=theme_set_id, + ) + instance = ComplianceRegistrationInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, registration_id: str) -> ComplianceRegistrationInquiriesContext: """ Constructs a ComplianceRegistrationInquiriesContext diff --git a/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py b/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py index 4d8988ab41..691594bd4f 100644 --- a/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py +++ b/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -22,6 +23,13 @@ class ComplianceTollfreeInquiriesInstance(InstanceResource): + class BusinessType(object): + PRIVATE_PROFIT = "PRIVATE_PROFIT" + PUBLIC_PROFIT = "PUBLIC_PROFIT" + NON_PROFIT = "NON_PROFIT" + SOLE_PROPRIETOR = "SOLE_PROPRIETOR" + GOVERNMENT = "GOVERNMENT" + class OptInType(object): VERBAL = "VERBAL" WEB_FORM = "WEB_FORM" @@ -67,10 +75,11 @@ def __init__(self, version: Version): self._uri = "/ComplianceInquiries/Tollfree/Initialize" - def create( + def _create( self, tollfree_phone_number: str, notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, business_name: Union[str, object] = values.unset, business_website: Union[str, object] = values.unset, use_case_categories: Union[List[str], object] = values.unset, @@ -94,41 +103,35 @@ def create( business_contact_phone: Union[str, object] = values.unset, theme_set_id: Union[str, object] = values.unset, skip_messaging_use_case: Union[bool, object] = values.unset, - ) -> ComplianceTollfreeInquiriesInstance: + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> tuple: """ - Create the ComplianceTollfreeInquiriesInstance + Internal helper for create operation - :param tollfree_phone_number: The Tollfree phone number to be verified - :param notification_email: The email address to receive the notification about the verification result. - :param business_name: The name of the business or organization using the Tollfree number. - :param business_website: The website of the business or organization using the Tollfree number. - :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. - :param use_case_summary: Use this to further explain how messaging is used by the business or organization. - :param production_message_sample: An example of message content, i.e. a sample message. - :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. - :param opt_in_type: - :param message_volume: Estimate monthly volume of messages from the Tollfree Number. - :param business_street_address: The address of the business or organization using the Tollfree number. - :param business_street_address2: The address of the business or organization using the Tollfree number. - :param business_city: The city of the business or organization using the Tollfree number. - :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. - :param business_postal_code: The postal code of the business or organization using the Tollfree number. - :param business_country: The country of the business or organization using the Tollfree number. - :param additional_information: Additional information to be provided for verification. - :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. - :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. - :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. - :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. - :param theme_set_id: Theme id for styling the inquiry form. - :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. - - :returns: The created ComplianceTollfreeInquiriesInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( { "TollfreePhoneNumber": tollfree_phone_number, "NotificationEmail": notification_email, + "CustomerProfileSid": customer_profile_sid, "BusinessName": business_name, "BusinessWebsite": business_website, "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), @@ -152,20 +155,37 @@ def create( "SkipMessagingUseCase": serialize.boolean_to_string( skip_messaging_use_case ), + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "ExternalReferenceId": external_reference_id, + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "VettingId": vetting_id, + "VettingProvider": vetting_provider, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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 ComplianceTollfreeInquiriesInstance(self._version, payload) - - async def create_async( + def create( self, tollfree_phone_number: str, notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, business_name: Union[str, object] = values.unset, business_website: Union[str, object] = values.unset, use_case_categories: Union[List[str], object] = values.unset, @@ -189,12 +209,29 @@ async def create_async( business_contact_phone: Union[str, object] = values.unset, theme_set_id: Union[str, object] = values.unset, skip_messaging_use_case: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, ) -> ComplianceTollfreeInquiriesInstance: """ - Asynchronously create the ComplianceTollfreeInquiriesInstance + Create the ComplianceTollfreeInquiriesInstance :param tollfree_phone_number: The Tollfree phone number to be verified :param notification_email: The email address to receive the notification about the verification result. + :param customer_profile_sid: The Customer Profile Sid associated with the Account. :param business_name: The name of the business or organization using the Tollfree number. :param business_website: The website of the business or organization using the Tollfree number. :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. @@ -216,14 +253,254 @@ async def create_async( :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. :param theme_set_id: Theme id for styling the inquiry form. :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. + :param business_registration_number: The Business Registration Number of the business or organization. + :param business_registration_authority: The Business Registration Authority of the business or organization. + :param business_registration_country: The Business Registration Country of the business or organization. + :param business_type: + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification. + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param external_reference_id: A legally recognized business registration number. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_id: Unique identifier for the created Vetting . + :param vetting_provider: Name of the vetting provider. :returns: The created ComplianceTollfreeInquiriesInstance """ + payload, _, _ = self._create( + tollfree_phone_number=tollfree_phone_number, + notification_email=notification_email, + customer_profile_sid=customer_profile_sid, + business_name=business_name, + business_website=business_website, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + theme_set_id=theme_set_id, + skip_messaging_use_case=skip_messaging_use_case, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + external_reference_id=external_reference_id, + opt_in_keywords=opt_in_keywords, + vetting_id=vetting_id, + vetting_provider=vetting_provider, + ) + return ComplianceTollfreeInquiriesInstance(self._version, payload) + + def create_with_http_info( + self, + tollfree_phone_number: str, + notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "ComplianceTollfreeInquiriesInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + skip_messaging_use_case: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ComplianceTollfreeInquiriesInstance and return response metadata + + :param tollfree_phone_number: The Tollfree phone number to be verified + :param notification_email: The email address to receive the notification about the verification result. + :param customer_profile_sid: The Customer Profile Sid associated with the Account. + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. + :param theme_set_id: Theme id for styling the inquiry form. + :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. + :param business_registration_number: The Business Registration Number of the business or organization. + :param business_registration_authority: The Business Registration Authority of the business or organization. + :param business_registration_country: The Business Registration Country of the business or organization. + :param business_type: + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification. + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param external_reference_id: A legally recognized business registration number. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_id: Unique identifier for the created Vetting . + :param vetting_provider: Name of the vetting provider. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + tollfree_phone_number=tollfree_phone_number, + notification_email=notification_email, + customer_profile_sid=customer_profile_sid, + business_name=business_name, + business_website=business_website, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + theme_set_id=theme_set_id, + skip_messaging_use_case=skip_messaging_use_case, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + external_reference_id=external_reference_id, + opt_in_keywords=opt_in_keywords, + vetting_id=vetting_id, + vetting_provider=vetting_provider, + ) + instance = ComplianceTollfreeInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + tollfree_phone_number: str, + notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "ComplianceTollfreeInquiriesInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + skip_messaging_use_case: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { "TollfreePhoneNumber": tollfree_phone_number, "NotificationEmail": notification_email, + "CustomerProfileSid": customer_profile_sid, "BusinessName": business_name, "BusinessWebsite": business_website, "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), @@ -247,16 +524,295 @@ async def create_async( "SkipMessagingUseCase": serialize.boolean_to_string( skip_messaging_use_case ), + "BusinessRegistrationNumber": business_registration_number, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessRegistrationCountry": business_registration_country, + "BusinessType": business_type, + "DoingBusinessAs": doing_business_as, + "OptInConfirmationMessage": opt_in_confirmation_message, + "HelpMessageSample": help_message_sample, + "PrivacyPolicyUrl": privacy_policy_url, + "TermsAndConditionsUrl": terms_and_conditions_url, + "AgeGatedContent": serialize.boolean_to_string(age_gated_content), + "ExternalReferenceId": external_reference_id, + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "VettingId": vetting_id, + "VettingProvider": vetting_provider, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, + tollfree_phone_number: str, + notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "ComplianceTollfreeInquiriesInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + skip_messaging_use_case: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> ComplianceTollfreeInquiriesInstance: + """ + Asynchronously create the ComplianceTollfreeInquiriesInstance + + :param tollfree_phone_number: The Tollfree phone number to be verified + :param notification_email: The email address to receive the notification about the verification result. + :param customer_profile_sid: The Customer Profile Sid associated with the Account. + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. + :param theme_set_id: Theme id for styling the inquiry form. + :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. + :param business_registration_number: The Business Registration Number of the business or organization. + :param business_registration_authority: The Business Registration Authority of the business or organization. + :param business_registration_country: The Business Registration Country of the business or organization. + :param business_type: + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification. + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param external_reference_id: A legally recognized business registration number. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_id: Unique identifier for the created Vetting . + :param vetting_provider: Name of the vetting provider. + + :returns: The created ComplianceTollfreeInquiriesInstance + """ + payload, _, _ = await self._create_async( + tollfree_phone_number=tollfree_phone_number, + notification_email=notification_email, + customer_profile_sid=customer_profile_sid, + business_name=business_name, + business_website=business_website, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + theme_set_id=theme_set_id, + skip_messaging_use_case=skip_messaging_use_case, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + external_reference_id=external_reference_id, + opt_in_keywords=opt_in_keywords, + vetting_id=vetting_id, + vetting_provider=vetting_provider, + ) return ComplianceTollfreeInquiriesInstance(self._version, payload) + async def create_with_http_info_async( + self, + tollfree_phone_number: str, + notification_email: str, + customer_profile_sid: Union[str, object] = values.unset, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "ComplianceTollfreeInquiriesInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + skip_messaging_use_case: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_registration_authority: Union[str, object] = values.unset, + business_registration_country: Union[str, object] = values.unset, + business_type: Union[ + "ComplianceTollfreeInquiriesInstance.BusinessType", object + ] = values.unset, + doing_business_as: Union[str, object] = values.unset, + opt_in_confirmation_message: Union[str, object] = values.unset, + help_message_sample: Union[str, object] = values.unset, + privacy_policy_url: Union[str, object] = values.unset, + terms_and_conditions_url: Union[str, object] = values.unset, + age_gated_content: Union[bool, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + vetting_id: Union[str, object] = values.unset, + vetting_provider: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the ComplianceTollfreeInquiriesInstance and return response metadata + + :param tollfree_phone_number: The Tollfree phone number to be verified + :param notification_email: The email address to receive the notification about the verification result. + :param customer_profile_sid: The Customer Profile Sid associated with the Account. + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. + :param theme_set_id: Theme id for styling the inquiry form. + :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. + :param business_registration_number: The Business Registration Number of the business or organization. + :param business_registration_authority: The Business Registration Authority of the business or organization. + :param business_registration_country: The Business Registration Country of the business or organization. + :param business_type: + :param doing_business_as: Trade name, sub entity, or downstream business name of business being submitted for verification. + :param opt_in_confirmation_message: The confirmation message sent to users when they opt in to receive messages. + :param help_message_sample: A sample help message provided to users. + :param privacy_policy_url: The URL to the privacy policy for the business or organization. + :param terms_and_conditions_url: The URL to the terms and conditions for the business or organization. + :param age_gated_content: Indicates if the content is age gated. + :param external_reference_id: A legally recognized business registration number. + :param opt_in_keywords: List of keywords that users can text in to opt in to receive messages. + :param vetting_id: Unique identifier for the created Vetting . + :param vetting_provider: Name of the vetting provider. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + tollfree_phone_number=tollfree_phone_number, + notification_email=notification_email, + customer_profile_sid=customer_profile_sid, + business_name=business_name, + business_website=business_website, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + theme_set_id=theme_set_id, + skip_messaging_use_case=skip_messaging_use_case, + business_registration_number=business_registration_number, + business_registration_authority=business_registration_authority, + business_registration_country=business_registration_country, + business_type=business_type, + doing_business_as=doing_business_as, + opt_in_confirmation_message=opt_in_confirmation_message, + help_message_sample=help_message_sample, + privacy_policy_url=privacy_policy_url, + terms_and_conditions_url=terms_and_conditions_url, + age_gated_content=age_gated_content, + external_reference_id=external_reference_id, + opt_in_keywords=opt_in_keywords, + vetting_id=vetting_id, + vetting_provider=vetting_provider, + ) + instance = ComplianceTollfreeInquiriesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/trusthub/v1/customer_profiles/__init__.py b/twilio/rest/trusthub/v1/customer_profiles/__init__.py index 5079b89e6d..5ba9df5ecb 100644 --- a/twilio/rest/trusthub/v1/customer_profiles/__init__.py +++ b/twilio/rest/trusthub/v1/customer_profiles/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CustomerProfilesContext] = None @property @@ -119,6 +121,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CustomerProfilesInstance": """ Fetch the CustomerProfilesInstance @@ -137,6 +157,24 @@ async def fetch_async(self) -> "CustomerProfilesInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: Union["CustomerProfilesInstance.Status", object] = values.unset, @@ -185,6 +223,54 @@ async def update_async( email=email, ) + def update_with_http_info( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CustomerProfilesInstance with HTTP info + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_with_http_info_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CustomerProfilesInstance with HTTP info + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + @property def customer_profiles_channel_endpoint_assignment( self, @@ -247,6 +333,20 @@ def __init__(self, version: Version, sid: str): CustomerProfilesEvaluationsList ] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CustomerProfilesInstance @@ -254,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: @@ -266,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: @@ -278,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: """ @@ -297,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, @@ -326,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, @@ -334,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( @@ -362,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( @@ -443,6 +727,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CustomerProfilesInstance: :param payload: Payload response from the API """ + return CustomerProfilesInstance(self._version, payload) def __repr__(self) -> str: @@ -467,22 +752,18 @@ def __init__(self, version: Version): self._uri = "/CustomerProfiles" - def create( + def _create( self, friendly_name: str, email: str, policy_sid: str, status_callback: Union[str, object] = values.unset, - ) -> CustomerProfilesInstance: + ) -> tuple: """ - Create the CustomerProfilesInstance - - :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. + Internal helper for create operation - :returns: The created CustomerProfilesInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -495,13 +776,15 @@ def create( ) headers = values.of({"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 CustomerProfilesInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, email: str, @@ -509,7 +792,7 @@ async def create_async( status_callback: Union[str, object] = values.unset, ) -> CustomerProfilesInstance: """ - Asynchronously create the CustomerProfilesInstance + Create the CustomerProfilesInstance :param friendly_name: The string that you assigned to describe the resource. :param email: The email address that will receive updates when the Customer-Profile resource changes status. @@ -518,6 +801,53 @@ async def create_async( :returns: The created CustomerProfilesInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + return CustomerProfilesInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the CustomerProfilesInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + instance = CustomerProfilesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -529,12 +859,65 @@ async def create_async( ) headers = values.of({"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, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> CustomerProfilesInstance: + """ + Asynchronously create the CustomerProfilesInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: The created CustomerProfilesInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) return CustomerProfilesInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CustomerProfilesInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + instance = CustomerProfilesInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, status: Union["CustomerProfilesInstance.Status", object] = values.unset, @@ -607,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, @@ -632,6 +1085,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -667,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( @@ -678,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, @@ -711,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( @@ -747,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 0369e51d5c..f0b451d0fa 100644 --- a/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py +++ b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( "customer_profile_sid": customer_profile_sid, "sid": sid or self.sid, } + self._context: Optional[CustomerProfilesChannelEndpointAssignmentContext] = None @property @@ -92,6 +94,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CustomerProfilesChannelEndpointAssignmentInstance": """ Fetch the CustomerProfilesChannelEndpointAssignmentInstance @@ -110,6 +130,24 @@ async def fetch_async(self) -> "CustomerProfilesChannelEndpointAssignmentInstanc """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -143,6 +181,20 @@ def __init__(self, version: Version, customer_profile_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CustomerProfilesChannelEndpointAssignmentInstance @@ -150,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: @@ -162,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: @@ -174,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: """ @@ -194,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: """ @@ -229,6 +365,7 @@ def get_instance( :param payload: Payload response from the API """ + return CustomerProfilesChannelEndpointAssignmentInstance( self._version, payload, @@ -264,16 +401,12 @@ def __init__(self, version: Version, customer_profile_sid: str): **self._solution ) - def create( - self, channel_endpoint_type: str, channel_endpoint_sid: str - ) -> CustomerProfilesChannelEndpointAssignmentInstance: + def _create(self, channel_endpoint_type: str, channel_endpoint_sid: str) -> tuple: """ - Create the CustomerProfilesChannelEndpointAssignmentInstance + 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( @@ -284,26 +417,65 @@ def create( ) headers = values.of({"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, 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( @@ -314,16 +486,57 @@ async def create_async( ) headers = values.of({"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, 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, @@ -390,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, @@ -413,6 +690,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( channel_endpoint_sid=channel_endpoint_sid, @@ -445,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( @@ -455,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, @@ -485,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( @@ -520,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 @@ -540,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( @@ -556,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 8fbb523b8a..992ac98822 100644 --- a/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py +++ b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -54,6 +55,7 @@ def __init__( "customer_profile_sid": customer_profile_sid, "sid": sid or self.sid, } + self._context: Optional[CustomerProfilesEntityAssignmentsContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CustomerProfilesEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CustomerProfilesEntityAssignmentsInstance": """ Fetch the CustomerProfilesEntityAssignmentsInstance @@ -108,6 +128,24 @@ async def fetch_async(self) -> "CustomerProfilesEntityAssignmentsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -145,6 +183,20 @@ def __init__(self, version: Version, customer_profile_sid: str, sid: str): ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CustomerProfilesEntityAssignmentsInstance @@ -152,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: @@ -164,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: @@ -176,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: """ @@ -196,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: """ @@ -233,6 +369,7 @@ def get_instance( :param payload: Payload response from the API """ + return CustomerProfilesEntityAssignmentsInstance( self._version, payload, @@ -268,13 +405,12 @@ def __init__(self, version: Version, customer_profile_sid: str): **self._solution ) - def create(self, object_sid: str) -> CustomerProfilesEntityAssignmentsInstance: + def _create(self, object_sid: str) -> tuple: """ - Create the CustomerProfilesEntityAssignmentsInstance + Internal helper for create operation - :param object_sid: The SID of an object bag that holds information of the different items. - - :returns: The created CustomerProfilesEntityAssignmentsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -284,25 +420,51 @@ def create(self, object_sid: str) -> CustomerProfilesEntityAssignmentsInstance: ) headers = values.of({"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, 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( @@ -312,16 +474,47 @@ async def create_async( ) headers = values.of({"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, 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, @@ -378,6 +571,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams CustomerProfilesEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + object_type=object_type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams CustomerProfilesEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + object_type=object_type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, object_type: Union[str, object] = values.unset, @@ -399,6 +648,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( object_type=object_type, @@ -428,6 +678,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -437,6 +688,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists CustomerProfilesEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists CustomerProfilesEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, object_type: Union[str, object] = values.unset, @@ -464,9 +771,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 CustomerProfilesEntityAssignmentsPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -496,12 +809,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 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: """ @@ -514,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( @@ -530,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 b5c3ba746e..7094e1c0f9 100644 --- a/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py +++ b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -65,6 +66,7 @@ def __init__( "customer_profile_sid": customer_profile_sid, "sid": sid or self.sid, } + self._context: Optional[CustomerProfilesEvaluationsContext] = None @property @@ -101,6 +103,24 @@ async def fetch_async(self) -> "CustomerProfilesEvaluationsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesEvaluationsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CustomerProfilesEvaluationsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -134,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 @@ -141,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: """ @@ -161,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: """ @@ -196,6 +270,7 @@ def get_instance( :param payload: Payload response from the API """ + return CustomerProfilesEvaluationsInstance( self._version, payload, @@ -231,13 +306,12 @@ def __init__(self, version: Version, customer_profile_sid: str): **self._solution ) - def create(self, policy_sid: str) -> CustomerProfilesEvaluationsInstance: + def _create(self, policy_sid: str) -> tuple: """ - Create the CustomerProfilesEvaluationsInstance + Internal helper for create operation - :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. - - :returns: The created CustomerProfilesEvaluationsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -247,25 +321,51 @@ def create(self, policy_sid: str) -> CustomerProfilesEvaluationsInstance: ) headers = values.of({"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, 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( @@ -275,16 +375,47 @@ async def create_async( ) headers = values.of({"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, 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, @@ -335,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, @@ -354,6 +535,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -380,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( @@ -388,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, @@ -412,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, @@ -439,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, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["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 CustomerProfilesEvaluationsPage(self._version, response, 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: """ @@ -454,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: """ @@ -466,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 42bdb155e0..bb7c7740b8 100644 --- a/twilio/rest/trusthub/v1/end_user.py +++ b/twilio/rest/trusthub/v1/end_user.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -55,6 +56,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EndUserContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EndUserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EndUserInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "EndUserInstance": """ Fetch the EndUserInstance @@ -108,6 +128,24 @@ async def fetch_async(self) -> "EndUserInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -144,6 +182,42 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the EndUserInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the EndUserInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -171,6 +245,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/EndUsers/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the EndUserInstance @@ -178,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: @@ -190,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: @@ -202,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: """ @@ -221,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, @@ -246,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, @@ -274,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: """ @@ -307,6 +549,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EndUserInstance: :param payload: Payload response from the API """ + return EndUserInstance(self._version, payload) def __repr__(self) -> str: @@ -331,20 +574,17 @@ def __init__(self, version: Version): self._uri = "/EndUsers" - def create( + def _create( self, friendly_name: str, type: str, attributes: Union[object, object] = values.unset, - ) -> EndUserInstance: + ) -> tuple: """ - Create the EndUserInstance - - :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. + Internal helper for create operation - :returns: The created EndUserInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -356,20 +596,22 @@ def create( ) headers = values.of({"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 EndUserInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, type: str, attributes: Union[object, object] = values.unset, ) -> EndUserInstance: """ - Asynchronously create the EndUserInstance + Create the EndUserInstance :param friendly_name: The string that you assigned to describe the resource. :param type: The type of end user of the Bundle resource - can be `individual` or `business`. @@ -377,6 +619,44 @@ async def create_async( :returns: The created EndUserInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return EndUserInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Create the EndUserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of end user of the Bundle resource - can be `individual` or `business`. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = EndUserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -387,12 +667,55 @@ async def create_async( ) headers = values.of({"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, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronously create the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of end user of the Bundle resource - can be `individual` or `business`. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The created EndUserInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) return EndUserInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the EndUserInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of end user of the Bundle resource - can be `individual` or `business`. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = EndUserInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -443,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, @@ -462,6 +835,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -488,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( @@ -496,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, @@ -520,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( @@ -547,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 d336385b25..8f2da577fb 100644 --- a/twilio/rest/trusthub/v1/end_user_type.py +++ b/twilio/rest/trusthub/v1/end_user_type.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EndUserTypeContext] = None @property @@ -79,6 +81,24 @@ async def fetch_async(self) -> "EndUserTypeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -106,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 @@ -113,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: """ @@ -132,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: """ @@ -162,6 +234,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EndUserTypeInstance: :param payload: Payload response from the API """ + return EndUserTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -236,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, @@ -255,6 +378,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -281,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( @@ -289,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, @@ -313,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( @@ -340,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 a39b1e0e65..ed7035da27 100644 --- a/twilio/rest/trusthub/v1/policies.py +++ b/twilio/rest/trusthub/v1/policies.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -42,6 +43,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PoliciesContext] = None @property @@ -77,6 +79,24 @@ async def fetch_async(self) -> "PoliciesInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PoliciesInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PoliciesInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -104,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 @@ -111,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: """ @@ -130,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: """ @@ -160,6 +232,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PoliciesInstance: :param payload: Payload response from the API """ + return PoliciesInstance(self._version, payload) def __repr__(self) -> str: @@ -234,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, @@ -253,6 +376,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -279,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( @@ -287,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, @@ -311,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( @@ -338,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 2336e1fefa..8020232292 100644 --- a/twilio/rest/trusthub/v1/supporting_document.py +++ b/twilio/rest/trusthub/v1/supporting_document.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -25,12 +26,12 @@ class SupportingDocumentInstance(InstanceResource): class Status(object): - DRAFT = "draft" - PENDING_REVIEW = "pending-review" - REJECTED = "rejected" - APPROVED = "approved" - EXPIRED = "expired" - PROVISIONALLY_APPROVED = "provisionally-approved" + DRAFT = "DRAFT" + PENDING_REVIEW = "PENDING_REVIEW" + REJECTED = "REJECTED" + APPROVED = "APPROVED" + EXPIRED = "EXPIRED" + PROVISIONALLY_APPROVED = "PROVISIONALLY_APPROVED" """ :ivar sid: The unique string created by Twilio to identify the Supporting Document resource. @@ -70,6 +71,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SupportingDocumentContext] = None @property @@ -105,6 +107,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SupportingDocumentInstance": """ Fetch the SupportingDocumentInstance @@ -123,6 +143,24 @@ async def fetch_async(self) -> "SupportingDocumentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -159,6 +197,42 @@ async def update_async( attributes=attributes, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the SupportingDocumentInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SupportingDocumentInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + attributes=attributes, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -186,6 +260,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/SupportingDocuments/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SupportingDocumentInstance @@ -193,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: @@ -205,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: @@ -217,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: """ @@ -236,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, @@ -261,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( @@ -291,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: """ @@ -326,6 +572,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentInstance: :param payload: Payload response from the API """ + return SupportingDocumentInstance(self._version, payload) def __repr__(self) -> str: @@ -350,20 +597,17 @@ def __init__(self, version: Version): self._uri = "/SupportingDocuments" - def create( + def _create( self, friendly_name: str, type: str, attributes: Union[object, object] = values.unset, - ) -> SupportingDocumentInstance: + ) -> tuple: """ - Create the SupportingDocumentInstance - - :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. + Internal helper for create operation - :returns: The created SupportingDocumentInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -375,20 +619,22 @@ def create( ) headers = values.of({"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 SupportingDocumentInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, type: str, attributes: Union[object, object] = values.unset, ) -> SupportingDocumentInstance: """ - Asynchronously create the SupportingDocumentInstance + Create the SupportingDocumentInstance :param friendly_name: The string that you assigned to describe the resource. :param type: The type of the Supporting Document. @@ -396,6 +642,44 @@ async def create_async( :returns: The created SupportingDocumentInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + return SupportingDocumentInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Create the SupportingDocumentInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = SupportingDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -406,12 +690,55 @@ async def create_async( ) headers = values.of({"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, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronously create the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: The created SupportingDocumentInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) return SupportingDocumentInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SupportingDocumentInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes + ) + instance = SupportingDocumentInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -462,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, @@ -481,6 +858,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -507,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( @@ -515,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, @@ -539,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( @@ -566,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 f1a93c59b7..2ae6cb345e 100644 --- a/twilio/rest/trusthub/v1/supporting_document_type.py +++ b/twilio/rest/trusthub/v1/supporting_document_type.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -44,6 +45,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SupportingDocumentTypeContext] = None @property @@ -79,6 +81,24 @@ async def fetch_async(self) -> "SupportingDocumentTypeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -106,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 @@ -113,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: """ @@ -132,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: """ @@ -162,6 +234,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentTypeInstanc :param payload: Payload response from the API """ + return SupportingDocumentTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -236,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, @@ -255,6 +378,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -281,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( @@ -289,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, @@ -313,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( @@ -340,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 c819eb0a07..3c2553dbbe 100644 --- a/twilio/rest/trusthub/v1/trust_products/__init__.py +++ b/twilio/rest/trusthub/v1/trust_products/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -84,6 +85,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[TrustProductsContext] = None @property @@ -119,6 +121,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TrustProductsInstance": """ Fetch the TrustProductsInstance @@ -137,6 +157,24 @@ async def fetch_async(self) -> "TrustProductsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: Union["TrustProductsInstance.Status", object] = values.unset, @@ -185,6 +223,54 @@ async def update_async( email=email, ) + def update_with_http_info( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the TrustProductsInstance with HTTP info + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_with_http_info_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the TrustProductsInstance with HTTP info + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + @property def trust_products_channel_endpoint_assignment( self, @@ -243,6 +329,20 @@ def __init__(self, version: Version, sid: str): ] = None self._trust_products_evaluations: Optional[TrustProductsEvaluationsList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TrustProductsInstance @@ -250,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: @@ -262,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: @@ -274,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: """ @@ -293,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, @@ -322,6 +536,56 @@ def update( :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, @@ -330,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, @@ -356,22 +621,41 @@ async def update_async( :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( @@ -433,6 +717,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TrustProductsInstance: :param payload: Payload response from the API """ + return TrustProductsInstance(self._version, payload) def __repr__(self) -> str: @@ -457,22 +742,18 @@ def __init__(self, version: Version): self._uri = "/TrustProducts" - def create( + def _create( self, friendly_name: str, email: str, policy_sid: str, status_callback: Union[str, object] = values.unset, - ) -> TrustProductsInstance: + ) -> tuple: """ - Create the TrustProductsInstance - - :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. + Internal helper for create operation - :returns: The created TrustProductsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -485,13 +766,15 @@ def create( ) headers = values.of({"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 TrustProductsInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, email: str, @@ -499,7 +782,7 @@ async def create_async( status_callback: Union[str, object] = values.unset, ) -> TrustProductsInstance: """ - Asynchronously create the TrustProductsInstance + Create the TrustProductsInstance :param friendly_name: The string that you assigned to describe the resource. :param email: The email address that will receive updates when the Trust Product resource changes status. @@ -508,6 +791,53 @@ async def create_async( :returns: The created TrustProductsInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + return TrustProductsInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the TrustProductsInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, + ) + instance = TrustProductsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -519,12 +849,65 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -597,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, @@ -622,6 +1075,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -657,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( @@ -668,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, @@ -701,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( @@ -737,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. 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 df69d31ddf..0f16a1a57c 100644 --- a/twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py +++ b/twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( "trust_product_sid": trust_product_sid, "sid": sid or self.sid, } + self._context: Optional[TrustProductsChannelEndpointAssignmentContext] = None @property @@ -92,6 +94,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TrustProductsChannelEndpointAssignmentInstance": """ Fetch the TrustProductsChannelEndpointAssignmentInstance @@ -110,6 +130,24 @@ async def fetch_async(self) -> "TrustProductsChannelEndpointAssignmentInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsChannelEndpointAssignmentInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -143,6 +181,20 @@ def __init__(self, version: Version, trust_product_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TrustProductsChannelEndpointAssignmentInstance @@ -150,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: @@ -162,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: @@ -174,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: """ @@ -194,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: """ @@ -229,6 +365,7 @@ def get_instance( :param payload: Payload response from the API """ + return TrustProductsChannelEndpointAssignmentInstance( self._version, payload, @@ -266,16 +403,12 @@ def __init__(self, version: Version, trust_product_sid: str): ) ) - def create( - self, channel_endpoint_type: str, channel_endpoint_sid: str - ) -> TrustProductsChannelEndpointAssignmentInstance: + def _create(self, channel_endpoint_type: str, channel_endpoint_sid: str) -> tuple: """ - Create the TrustProductsChannelEndpointAssignmentInstance + 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( @@ -286,26 +419,65 @@ def create( ) headers = values.of({"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, 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( @@ -316,16 +488,57 @@ async def create_async( ) headers = values.of({"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, 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, @@ -392,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, @@ -415,6 +692,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( channel_endpoint_sid=channel_endpoint_sid, @@ -447,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( @@ -457,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, @@ -487,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( @@ -522,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: """ @@ -540,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( @@ -556,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 57e1b3119c..f4525abc80 100644 --- a/twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py +++ b/twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -54,6 +55,7 @@ def __init__( "trust_product_sid": trust_product_sid, "sid": sid or self.sid, } + self._context: Optional[TrustProductsEntityAssignmentsContext] = None @property @@ -90,6 +92,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the TrustProductsEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "TrustProductsEntityAssignmentsInstance": """ Fetch the TrustProductsEntityAssignmentsInstance @@ -108,6 +128,24 @@ async def fetch_async(self) -> "TrustProductsEntityAssignmentsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsEntityAssignmentsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -141,6 +179,20 @@ def __init__(self, version: Version, trust_product_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the TrustProductsEntityAssignmentsInstance @@ -148,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: @@ -160,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: @@ -172,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: """ @@ -192,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: """ @@ -227,6 +363,7 @@ def get_instance( :param payload: Payload response from the API """ + return TrustProductsEntityAssignmentsInstance( self._version, payload, @@ -262,13 +399,12 @@ def __init__(self, version: Version, trust_product_sid: str): **self._solution ) - def create(self, object_sid: str) -> TrustProductsEntityAssignmentsInstance: + def _create(self, object_sid: str) -> tuple: """ - Create the TrustProductsEntityAssignmentsInstance + Internal helper for create operation - :param object_sid: The SID of an object bag that holds information of the different items. - - :returns: The created TrustProductsEntityAssignmentsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -278,25 +414,51 @@ def create(self, object_sid: str) -> TrustProductsEntityAssignmentsInstance: ) headers = values.of({"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, 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( @@ -306,16 +468,47 @@ async def create_async( ) headers = values.of({"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, 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, @@ -372,6 +565,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TrustProductsEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + object_type=object_type, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TrustProductsEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + object_type=object_type, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, object_type: Union[str, object] = values.unset, @@ -393,6 +642,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( object_type=object_type, @@ -422,6 +672,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -431,6 +682,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TrustProductsEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TrustProductsEntityAssignmentsInstance and returns headers from first page + + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, object_type: Union[str, object] = values.unset, @@ -458,9 +765,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 TrustProductsEntityAssignmentsPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -490,12 +803,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 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: """ @@ -508,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( @@ -524,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 3088a2b1b4..f27af2615f 100644 --- a/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py +++ b/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -65,6 +66,7 @@ def __init__( "trust_product_sid": trust_product_sid, "sid": sid or self.sid, } + self._context: Optional[TrustProductsEvaluationsContext] = None @property @@ -101,6 +103,24 @@ async def fetch_async(self) -> "TrustProductsEvaluationsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsEvaluationsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the TrustProductsEvaluationsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -134,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 @@ -141,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: """ @@ -161,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: """ @@ -192,6 +266,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TrustProductsEvaluationsInsta :param payload: Payload response from the API """ + return TrustProductsEvaluationsInstance( self._version, payload, @@ -227,13 +302,12 @@ def __init__(self, version: Version, trust_product_sid: str): **self._solution ) - def create(self, policy_sid: str) -> TrustProductsEvaluationsInstance: + def _create(self, policy_sid: str) -> tuple: """ - Create the TrustProductsEvaluationsInstance - - :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( @@ -243,23 +317,51 @@ def create(self, policy_sid: str) -> TrustProductsEvaluationsInstance: ) headers = values.of({"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, 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( @@ -269,16 +371,45 @@ async def create_async(self, policy_sid: str) -> TrustProductsEvaluationsInstanc ) headers = values.of({"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, 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, @@ -329,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, @@ -348,6 +529,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -374,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( @@ -382,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, @@ -406,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, @@ -433,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 ) - return TrustProductsEvaluationsPage(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 TrustProductsEvaluationsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = TrustProductsEvaluationsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with TrustProductsEvaluationsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = TrustProductsEvaluationsPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> TrustProductsEvaluationsPage: """ @@ -448,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: """ @@ -460,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/v2/form.py b/twilio/rest/verify/v2/form.py index 6e3231fcda..223f6b6d15 100644 --- a/twilio/rest/verify/v2/form.py +++ b/twilio/rest/verify/v2/form.py @@ -13,6 +13,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 @@ -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 @@ -109,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 @@ -116,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: """ @@ -135,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: """ diff --git a/twilio/rest/verify/v2/safelist.py b/twilio/rest/verify/v2/safelist.py index 0ee946a342..9ea8069e48 100644 --- a/twilio/rest/verify/v2/safelist.py +++ b/twilio/rest/verify/v2/safelist.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -42,6 +43,7 @@ def __init__( self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[SafelistContext] = None @property @@ -77,6 +79,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SafelistInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SafelistInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SafelistInstance": """ Fetch the SafelistInstance @@ -95,6 +115,24 @@ async def fetch_async(self) -> "SafelistInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SafelistInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SafelistInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -122,6 +160,20 @@ def __init__(self, version: Version, phone_number: str): } self._uri = "/SafeList/Numbers/{phone_number}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SafelistInstance @@ -129,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: @@ -141,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: @@ -153,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: """ @@ -172,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: """ @@ -207,13 +341,12 @@ def __init__(self, version: Version): self._uri = "/SafeList/Numbers" - def create(self, phone_number: str) -> SafelistInstance: + def _create(self, phone_number: str) -> tuple: """ - Create the SafelistInstance + Internal helper for create operation - :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). - - :returns: The created SafelistInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -223,19 +356,43 @@ def create(self, phone_number: str) -> SafelistInstance: ) headers = values.of({"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, 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( @@ -245,12 +402,39 @@ async def create_async(self, phone_number: str) -> SafelistInstance: ) headers = values.of({"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, 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 69a6cf853e..ed9b7747be 100644 --- a/twilio/rest/verify/v2/service/__init__.py +++ b/twilio/rest/verify/v2/service/__init__.py @@ -15,16 +15,21 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from twilio.base.version import Version from twilio.base.page import Page from twilio.rest.verify.v2.service.access_token import AccessTokenList +from twilio.rest.verify.v2.service.approve_challenge import ApproveChallengeList from twilio.rest.verify.v2.service.entity import EntityList from twilio.rest.verify.v2.service.messaging_configuration import ( MessagingConfigurationList, ) +from twilio.rest.verify.v2.service.new_challenge import NewChallengeList +from twilio.rest.verify.v2.service.new_factor import NewFactorList +from twilio.rest.verify.v2.service.new_verify_factor import NewVerifyFactorList from twilio.rest.verify.v2.service.rate_limit import RateLimitList from twilio.rest.verify.v2.service.verification import VerificationList from twilio.rest.verify.v2.service.verification_check import VerificationCheckList @@ -35,7 +40,7 @@ class ServiceInstance(InstanceResource): """ :ivar sid: The unique string that we created to identify the Service resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. - :ivar friendly_name: The name that appears in the body of your verification messages. It can be up to 30 characters long and can include letters, numbers, spaces, dashes, underscores. Phone numbers, special characters or links are NOT allowed. **This value should not contain PII.** + :ivar friendly_name: The name that appears in the body of your verification messages. It can be up to 30 characters long and can include letters, numbers, spaces, dashes, underscores. Phone numbers, special characters or links are NOT allowed. It cannot contain more than 4 (consecutive or non-consecutive) digits. **This value should not contain PII.** :ivar code_length: The length of the verification code to generate. :ivar lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. :ivar psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. @@ -43,11 +48,12 @@ 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. @@ -81,6 +87,7 @@ def __init__( self.totp: Optional[Dict[str, object]] = payload.get("totp") self.default_template_sid: Optional[str] = payload.get("default_template_sid") self.whatsapp: Optional[Dict[str, object]] = payload.get("whatsapp") + self.passkeys: Optional[Dict[str, object]] = payload.get("passkeys") self.verify_event_subscription_enabled: Optional[bool] = payload.get( "verify_event_subscription_enabled" ) @@ -96,6 +103,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -131,6 +139,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ServiceInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ServiceInstance": """ Fetch the ServiceInstance @@ -149,6 +175,24 @@ async def fetch_async(self) -> "ServiceInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ServiceInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -170,6 +214,12 @@ def update( default_template_sid: Union[str, object] = values.unset, whatsapp_msg_service_sid: Union[str, object] = values.unset, whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, verify_event_subscription_enabled: Union[bool, object] = values.unset, ) -> "ServiceInstance": """ @@ -183,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) @@ -194,6 +244,12 @@ def update( :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured :returns: The updated ServiceInstance @@ -218,6 +274,12 @@ def update( default_template_sid=default_template_sid, whatsapp_msg_service_sid=whatsapp_msg_service_sid, whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, verify_event_subscription_enabled=verify_event_subscription_enabled, ) @@ -242,6 +304,12 @@ async def update_async( default_template_sid: Union[str, object] = values.unset, whatsapp_msg_service_sid: Union[str, object] = values.unset, whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, verify_event_subscription_enabled: Union[bool, object] = values.unset, ) -> "ServiceInstance": """ @@ -255,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) @@ -266,6 +334,12 @@ async def update_async( :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured :returns: The updated ServiceInstance @@ -290,6 +364,192 @@ async def update_async( default_template_sid=default_template_sid, whatsapp_msg_service_sid=whatsapp_msg_service_sid, whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ServiceInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, verify_event_subscription_enabled=verify_event_subscription_enabled, ) @@ -300,6 +560,13 @@ def access_tokens(self) -> AccessTokenList: """ return self._proxy.access_tokens + @property + def approve_challenge(self) -> ApproveChallengeList: + """ + Access the approve_challenge + """ + return self._proxy.approve_challenge + @property def entities(self) -> EntityList: """ @@ -314,6 +581,27 @@ def messaging_configurations(self) -> MessagingConfigurationList: """ return self._proxy.messaging_configurations + @property + def new_challenge(self) -> NewChallengeList: + """ + Access the new_challenge + """ + return self._proxy.new_challenge + + @property + def new_factors(self) -> NewFactorList: + """ + Access the new_factors + """ + return self._proxy.new_factors + + @property + def new_verify_factors(self) -> NewVerifyFactorList: + """ + Access the new_verify_factors + """ + return self._proxy.new_verify_factors + @property def rate_limits(self) -> RateLimitList: """ @@ -370,13 +658,31 @@ def __init__(self, version: Version, sid: str): self._uri = "/Services/{sid}".format(**self._solution) self._access_tokens: Optional[AccessTokenList] = None + self._approve_challenge: Optional[ApproveChallengeList] = None self._entities: Optional[EntityList] = None self._messaging_configurations: Optional[MessagingConfigurationList] = None + self._new_challenge: Optional[NewChallengeList] = None + self._new_factors: Optional[NewFactorList] = None + self._new_verify_factors: Optional[NewVerifyFactorList] = None self._rate_limits: Optional[RateLimitList] = None self._verifications: Optional[VerificationList] = None self._verification_checks: Optional[VerificationCheckList] = None self._webhooks: Optional[WebhookList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ServiceInstance @@ -384,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: @@ -396,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: @@ -408,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: """ @@ -427,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, @@ -460,34 +848,21 @@ def update( default_template_sid: Union[str, object] = values.unset, whatsapp_msg_service_sid: Union[str, object] = values.unset, whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, verify_event_subscription_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> tuple: """ - Update the ServiceInstance - - :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. 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. - :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. - :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. - :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + Internal helper for update operation - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -513,22 +888,29 @@ def update( "DefaultTemplateSid": default_template_sid, "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, "Whatsapp.From": whatsapp_from, + "Passkeys.RelyingParty.Id": passkeys_relying_party_id, + "Passkeys.RelyingParty.Name": passkeys_relying_party_name, + "Passkeys.RelyingParty.Origins": passkeys_relying_party_origins, + "Passkeys.AuthenticatorAttachment": passkeys_authenticator_attachment, + "Passkeys.DiscoverableCredentials": passkeys_discoverable_credentials, + "Passkeys.UserVerification": passkeys_user_verification, "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( verify_event_subscription_enabled ), } ) + 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( - self, + 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, lookup_enabled: Union[bool, object] = values.unset, @@ -548,10 +930,16 @@ async def update_async( default_template_sid: Union[str, object] = values.unset, whatsapp_msg_service_sid: Union[str, object] = values.unset, whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, verify_event_subscription_enabled: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Asynchronous coroutine to update the ServiceInstance + Update the ServiceInstance :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. @@ -561,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) @@ -572,10 +960,174 @@ async def update_async( :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured :returns: The updated ServiceInstance """ + payload, _, _ = self._update( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + instance = ServiceInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "FriendlyName": friendly_name, @@ -601,70 +1153,308 @@ async def update_async( "DefaultTemplateSid": default_template_sid, "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, "Whatsapp.From": whatsapp_from, + "Passkeys.RelyingParty.Id": passkeys_relying_party_id, + "Passkeys.RelyingParty.Name": passkeys_relying_party_name, + "Passkeys.RelyingParty.Origins": passkeys_relying_party_origins, + "Passkeys.AuthenticatorAttachment": passkeys_authenticator_attachment, + "Passkeys.DiscoverableCredentials": passkeys_discoverable_credentials, + "Passkeys.UserVerification": passkeys_user_verification, "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( verify_event_subscription_enabled ), } ) + 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 ServiceInstance(self._version, payload, sid=self._solution["sid"]) + headers["Accept"] = "application/json" - @property - def access_tokens(self) -> AccessTokenList: - """ - Access the access_tokens - """ - if self._access_tokens is None: - self._access_tokens = AccessTokenList( - self._version, - self._solution["sid"], - ) - return self._access_tokens + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def entities(self) -> EntityList: - """ - Access the entities + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: """ - if self._entities is None: - self._entities = EntityList( - self._version, - self._solution["sid"], - ) - return self._entities + Asynchronous coroutine to update the ServiceInstance - @property - def messaging_configurations(self) -> MessagingConfigurationList: - """ - Access the messaging_configurations - """ - if self._messaging_configurations is None: - self._messaging_configurations = MessagingConfigurationList( - self._version, - self._solution["sid"], - ) - return self._messaging_configurations + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured - @property - def rate_limits(self) -> RateLimitList: - """ - Access the rate_limits + :returns: The updated ServiceInstance """ - if self._rate_limits is None: - self._rate_limits = RateLimitList( - self._version, - self._solution["sid"], - ) - return self._rate_limits + payload, _, _ = await self._update_async( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - @property - def verifications(self) -> VerificationList: + 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, + self._solution["sid"], + ) + return self._access_tokens + + @property + def approve_challenge(self) -> ApproveChallengeList: + """ + Access the approve_challenge + """ + if self._approve_challenge is None: + self._approve_challenge = ApproveChallengeList( + self._version, + self._solution["sid"], + ) + return self._approve_challenge + + @property + def entities(self) -> EntityList: + """ + Access the entities + """ + if self._entities is None: + self._entities = EntityList( + self._version, + self._solution["sid"], + ) + return self._entities + + @property + def messaging_configurations(self) -> MessagingConfigurationList: + """ + Access the messaging_configurations + """ + if self._messaging_configurations is None: + self._messaging_configurations = MessagingConfigurationList( + self._version, + self._solution["sid"], + ) + return self._messaging_configurations + + @property + def new_challenge(self) -> NewChallengeList: + """ + Access the new_challenge + """ + if self._new_challenge is None: + self._new_challenge = NewChallengeList( + self._version, + self._solution["sid"], + ) + return self._new_challenge + + @property + def new_factors(self) -> NewFactorList: + """ + Access the new_factors + """ + if self._new_factors is None: + self._new_factors = NewFactorList( + self._version, + self._solution["sid"], + ) + return self._new_factors + + @property + def new_verify_factors(self) -> NewVerifyFactorList: + """ + Access the new_verify_factors + """ + if self._new_verify_factors is None: + self._new_verify_factors = NewVerifyFactorList( + self._version, + self._solution["sid"], + ) + return self._new_verify_factors + + @property + def rate_limits(self) -> RateLimitList: + """ + Access the rate_limits + """ + if self._rate_limits is None: + self._rate_limits = RateLimitList( + self._version, + self._solution["sid"], + ) + return self._rate_limits + + @property + def verifications(self) -> VerificationList: """ Access the verifications """ @@ -717,6 +1507,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: :param payload: Payload response from the API """ + return ServiceInstance(self._version, payload) def __repr__(self) -> str: @@ -734,14 +1525,361 @@ def __init__(self, version: Version): """ Initialize the ServiceList - :param version: Version that contains the resource + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def _create( + self, + friendly_name: str, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CodeLength": code_length, + "LookupEnabled": serialize.boolean_to_string(lookup_enabled), + "SkipSmsToLandlines": serialize.boolean_to_string( + skip_sms_to_landlines + ), + "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), + "TtsName": tts_name, + "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), + "DoNotShareWarningEnabled": serialize.boolean_to_string( + do_not_share_warning_enabled + ), + "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), + "Push.IncludeDate": serialize.boolean_to_string(push_include_date), + "Push.ApnCredentialSid": push_apn_credential_sid, + "Push.FcmCredentialSid": push_fcm_credential_sid, + "Totp.Issuer": totp_issuer, + "Totp.TimeStep": totp_time_step, + "Totp.CodeLength": totp_code_length, + "Totp.Skew": totp_skew, + "DefaultTemplateSid": default_template_sid, + "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, + "Whatsapp.From": whatsapp_from, + "Passkeys.RelyingParty.Id": passkeys_relying_party_id, + "Passkeys.RelyingParty.Name": passkeys_relying_party_name, + "Passkeys.RelyingParty.Origins": passkeys_relying_party_origins, + "Passkeys.AuthenticatorAttachment": passkeys_authenticator_attachment, + "Passkeys.DiscoverableCredentials": passkeys_discoverable_credentials, + "Passkeys.UserVerification": passkeys_user_verification, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, + friendly_name: str, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a security warning at the end of an SMS verification body. Disabled by default and applies only to SMS. Example SMS body: `Your AppName verification code is: 1234. Don’t share this code with anyone; our employees will never ask for the code` + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. This timestamp value is the same one as the one found in `date_created`, please use that one instead. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. Defaults to the service friendly name if not provided. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. + :param whatsapp_from: The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The created ServiceInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + return ServiceInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the ServiceInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a security warning at the end of an SMS verification body. Disabled by default and applies only to SMS. Example SMS body: `Your AppName verification code is: 1234. Don’t share this code with anyone; our employees will never ask for the code` + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. This timestamp value is the same one as the one found in `date_created`, please use that one instead. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. Defaults to the service friendly name if not provided. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. + :param whatsapp_from: The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CodeLength": code_length, + "LookupEnabled": serialize.boolean_to_string(lookup_enabled), + "SkipSmsToLandlines": serialize.boolean_to_string( + skip_sms_to_landlines + ), + "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), + "TtsName": tts_name, + "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), + "DoNotShareWarningEnabled": serialize.boolean_to_string( + do_not_share_warning_enabled + ), + "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), + "Push.IncludeDate": serialize.boolean_to_string(push_include_date), + "Push.ApnCredentialSid": push_apn_credential_sid, + "Push.FcmCredentialSid": push_fcm_credential_sid, + "Totp.Issuer": totp_issuer, + "Totp.TimeStep": totp_time_step, + "Totp.CodeLength": totp_code_length, + "Totp.Skew": totp_skew, + "DefaultTemplateSid": default_template_sid, + "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, + "Whatsapp.From": whatsapp_from, + "Passkeys.RelyingParty.Id": passkeys_relying_party_id, + "Passkeys.RelyingParty.Name": passkeys_relying_party_name, + "Passkeys.RelyingParty.Origins": passkeys_relying_party_origins, + "Passkeys.AuthenticatorAttachment": passkeys_authenticator_attachment, + "Passkeys.DiscoverableCredentials": passkeys_discoverable_credentials, + "Passkeys.UserVerification": passkeys_user_verification, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - """ - 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: str, code_length: Union[int, object] = values.unset, @@ -762,10 +1900,16 @@ def create( default_template_sid: Union[str, object] = values.unset, whatsapp_msg_service_sid: Union[str, object] = values.unset, whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, verify_event_subscription_enabled: Union[bool, object] = values.unset, ) -> ServiceInstance: """ - Create the ServiceInstance + Asynchronously create the ServiceInstance :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. @@ -775,7 +1919,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) @@ -786,50 +1930,47 @@ def create( :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. :param whatsapp_msg_service_sid: The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. :param whatsapp_from: The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured :returns: The created ServiceInstance """ - - data = values.of( - { - "FriendlyName": friendly_name, - "CodeLength": code_length, - "LookupEnabled": serialize.boolean_to_string(lookup_enabled), - "SkipSmsToLandlines": serialize.boolean_to_string( - skip_sms_to_landlines - ), - "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), - "TtsName": tts_name, - "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), - "DoNotShareWarningEnabled": serialize.boolean_to_string( - do_not_share_warning_enabled - ), - "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), - "Push.IncludeDate": serialize.boolean_to_string(push_include_date), - "Push.ApnCredentialSid": push_apn_credential_sid, - "Push.FcmCredentialSid": push_fcm_credential_sid, - "Totp.Issuer": totp_issuer, - "Totp.TimeStep": totp_time_step, - "Totp.CodeLength": totp_code_length, - "Totp.Skew": totp_skew, - "DefaultTemplateSid": default_template_sid, - "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, - "Whatsapp.From": whatsapp_from, - "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( - verify_event_subscription_enabled - ), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, ) - return ServiceInstance(self._version, payload) - async def create_async( + async def create_with_http_info_async( self, friendly_name: str, code_length: Union[int, object] = values.unset, @@ -850,10 +1991,16 @@ async def create_async( default_template_sid: Union[str, object] = values.unset, whatsapp_msg_service_sid: Union[str, object] = values.unset, whatsapp_from: Union[str, object] = values.unset, + passkeys_relying_party_id: Union[str, object] = values.unset, + passkeys_relying_party_name: Union[str, object] = values.unset, + passkeys_relying_party_origins: Union[str, object] = values.unset, + passkeys_authenticator_attachment: Union[str, object] = values.unset, + passkeys_discoverable_credentials: Union[str, object] = values.unset, + passkeys_user_verification: Union[str, object] = values.unset, verify_event_subscription_enabled: Union[bool, object] = values.unset, - ) -> ServiceInstance: + ) -> ApiResponse: """ - Asynchronously create the ServiceInstance + Asynchronously create the ServiceInstance and return response metadata :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. @@ -863,7 +2010,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) @@ -874,48 +2021,46 @@ async def create_async( :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. :param whatsapp_msg_service_sid: The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. :param whatsapp_from: The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. + :param passkeys_relying_party_id: The Relying Party ID for Passkeys. This is the domain of your application, e.g. `example.com`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_name: The Relying Party Name for Passkeys. This is the name of your application, e.g. `Example App`. It is used to identify your application when creating Passkeys. + :param passkeys_relying_party_origins: The Relying Party Origins for Passkeys. This is the origin of your application, e.g. `login.example.com,www.example.com`. It is used to identify your application when creating Passkeys, it can have multiple origins split by `,`. + :param passkeys_authenticator_attachment: The Authenticator Attachment for Passkeys. This is the type of authenticator that will be used to create Passkeys. It can be empty or it can have the values `platform`, `cross-platform` or `any`. + :param passkeys_discoverable_credentials: Indicates whether credentials must be discoverable by the authenticator. It can be empty or it can have the values `required`, `preferred` or `discouraged`. + :param passkeys_user_verification: The User Verification for Passkeys. This is the type of user verification that will be used to create Passkeys. It can be empty or it can have the values `required`, `preferred` or `discouraged`. :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured - :returns: The created ServiceInstance + :returns: ApiResponse with instance, status code, and headers """ - - data = values.of( - { - "FriendlyName": friendly_name, - "CodeLength": code_length, - "LookupEnabled": serialize.boolean_to_string(lookup_enabled), - "SkipSmsToLandlines": serialize.boolean_to_string( - skip_sms_to_landlines - ), - "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), - "TtsName": tts_name, - "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), - "DoNotShareWarningEnabled": serialize.boolean_to_string( - do_not_share_warning_enabled - ), - "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), - "Push.IncludeDate": serialize.boolean_to_string(push_include_date), - "Push.ApnCredentialSid": push_apn_credential_sid, - "Push.FcmCredentialSid": push_fcm_credential_sid, - "Totp.Issuer": totp_issuer, - "Totp.TimeStep": totp_time_step, - "Totp.CodeLength": totp_code_length, - "Totp.Skew": totp_skew, - "DefaultTemplateSid": default_template_sid, - "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, - "Whatsapp.From": whatsapp_from, - "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( - verify_event_subscription_enabled - ), - } - ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data, headers=headers + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + passkeys_relying_party_id=passkeys_relying_party_id, + passkeys_relying_party_name=passkeys_relying_party_name, + passkeys_relying_party_origins=passkeys_relying_party_origins, + passkeys_authenticator_attachment=passkeys_authenticator_attachment, + passkeys_discoverable_credentials=passkeys_discoverable_credentials, + passkeys_user_verification=passkeys_user_verification, + verify_event_subscription_enabled=verify_event_subscription_enabled, ) - - return ServiceInstance(self._version, payload) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -967,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, @@ -986,6 +2181,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -1012,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( @@ -1020,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, @@ -1044,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( @@ -1071,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 917abbc965..a5ecc856b6 100644 --- a/twilio/rest/verify/v2/service/access_token.py +++ b/twilio/rest/verify/v2/service/access_token.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -67,6 +68,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[AccessTokenContext] = None @property @@ -103,6 +105,24 @@ async def fetch_async(self) -> "AccessTokenInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccessTokenInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AccessTokenInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -134,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 @@ -141,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: """ @@ -161,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: """ @@ -202,22 +276,18 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/AccessTokens".format(**self._solution) - def create( + def _create( self, identity: str, factor_type: "AccessTokenInstance.FactorTypes", factor_friendly_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> AccessTokenInstance: + ) -> tuple: """ - Create the AccessTokenInstance - - :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. - :param factor_type: - :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token - :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + Internal helper for create operation - :returns: The created AccessTokenInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -230,30 +300,81 @@ def create( ) headers = values.of({"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, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> AccessTokenInstance: + """ + Create the AccessTokenInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. + :param factor_type: + :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token + :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + + :returns: The created AccessTokenInstance + """ + payload, _, _ = self._create( + identity=identity, + factor_type=factor_type, + factor_friendly_name=factor_friendly_name, + ttl=ttl, + ) return AccessTokenInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, identity: str, factor_type: "AccessTokenInstance.FactorTypes", factor_friendly_name: Union[str, object] = values.unset, ttl: Union[int, object] = values.unset, - ) -> AccessTokenInstance: + ) -> ApiResponse: """ - Asynchronously create the AccessTokenInstance + Create the AccessTokenInstance and return response metadata :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. :param factor_type: :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. - :returns: The created AccessTokenInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + identity=identity, + factor_type=factor_type, + factor_friendly_name=factor_friendly_name, + ttl=ttl, + ) + instance = AccessTokenInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -266,14 +387,69 @@ async def create_async( ) headers = values.of({"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, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> AccessTokenInstance: + """ + Asynchronously create the AccessTokenInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. + :param factor_type: + :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token + :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + + :returns: The created AccessTokenInstance + """ + payload, _, _ = await self._create_async( + identity=identity, + factor_type=factor_type, + factor_friendly_name=factor_friendly_name, + ttl=ttl, + ) return AccessTokenInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the AccessTokenInstance and return response metadata + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. + :param factor_type: + :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token + :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + identity=identity, + factor_type=factor_type, + factor_friendly_name=factor_friendly_name, + ttl=ttl, + ) + instance = AccessTokenInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, sid: str) -> AccessTokenContext: """ Constructs a AccessTokenContext diff --git a/twilio/rest/verify/v2/service/approve_challenge.py b/twilio/rest/verify/v2/service/approve_challenge.py new file mode 100644 index 0000000000..52af951f0c --- /dev/null +++ b/twilio/rest/verify/v2/service/approve_challenge.py @@ -0,0 +1,346 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ApproveChallengeInstance(InstanceResource): + + class ApprovePasskeysChallengeRequest(object): + """ + :ivar id: A [base64url](https://base64.guru/standards/base64url) encoded representation of `rawId`. + :ivar raw_id: The globally unique identifier for this `PublicKeyCredential`. + :ivar authenticator_attachment: A string that indicates the mechanism by which the WebAuthn implementation is attached to the authenticator at the time the associated `navigator.credentials.create()` or `navigator.credentials.get()` call completes. + :ivar type: The valid credential types supported by the API. The values of this enumeration are used for versioning the `AuthenticatorAssertion` and `AuthenticatorAttestation` structures according to the type of the authenticator. + :ivar response: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.raw_id: Optional[str] = payload.get("rawId") + self.authenticator_attachment: Optional["ApproveChallengeInstance.str"] = ( + payload.get("authenticatorAttachment") + ) + self.type: Optional["ApproveChallengeInstance.str"] = payload.get("type") + self.response: Optional[ + ApproveChallengeList.ApprovePasskeysChallengeRequestResponse + ] = payload.get("response") + + def to_dict(self): + return { + "id": self.id, + "rawId": self.raw_id, + "authenticatorAttachment": self.authenticator_attachment, + "type": self.type, + "response": ( + self.response.to_dict() if self.response is not None else None + ), + } + + class ApprovePasskeysChallengeRequestResponse(object): + """ + :ivar authenticator_data: The [authenticator data](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data) structure contains information from the authenticator about the processing of a credential creation or authentication request. + :ivar client_data_json: This property contains the JSON-compatible serialization of the data passed from the browser to the authenticator in order to generate this credential. + :ivar signature: An assertion signature over `authenticatorData` and `clientDataJSON`. The assertion signature is created with the private key of the key pair that was created during the originating `navigator.credentials.create()` call and verified using the public key of that same key pair. + :ivar user_handle: The user handle stored in the authenticator, specified as `user.id` in the options passed to the originating `navigator.credentials.create()` call. This property should contain a base64url-encoded entity SID. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.authenticator_data: Optional[str] = payload.get("authenticatorData") + self.client_data_json: Optional[str] = payload.get("clientDataJSON") + self.signature: Optional[str] = payload.get("signature") + self.user_handle: Optional[str] = payload.get("userHandle") + + def to_dict(self): + return { + "authenticatorData": self.authenticator_data, + "clientDataJSON": self.client_data_json, + "signature": self.signature, + "userHandle": self.user_handle, + } + + """ + :ivar sid: A 34 character string that uniquely identifies this Challenge. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Challenge. + :ivar factor_sid: The unique SID identifier of the Factor. + :ivar date_created: The date that this Challenge was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Challenge was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_responded: The date that this Challenge was responded, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar status: The Status of this Challenge. One of `pending`, `expired`, `approved` or `denied`. + :ivar responded_reason: Reason for the Challenge to be in certain `status`. One of `none`, `not_needed` or `not_requested`. + :ivar details: Details provided to give context about the Challenge. + :ivar hidden_details: Details provided to give context about the Challenge. + :ivar metadata: Custom metadata associated with the challenge. + :ivar factor_type: The Factor Type of this Challenge. Currently `push` and `totp` are supported. + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Challenge. + :ivar options: An object that contains challenge options. Currently only used for `passkeys`. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.factor_sid: Optional[str] = payload.get("factor_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.date_responded: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_responded") + ) + self.expiration_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("expiration_date") + ) + self.status: Optional["ApproveChallengeInstance.str"] = payload.get("status") + self.responded_reason: Optional["ApproveChallengeInstance.str"] = payload.get( + "responded_reason" + ) + self.details: Optional[Dict[str, object]] = payload.get("details") + self.hidden_details: Optional[Dict[str, object]] = payload.get("hidden_details") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.factor_type: Optional["ApproveChallengeInstance.str"] = payload.get( + "factor_type" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.options: Optional[Dict[str, object]] = payload.get("options") + + self._solution = { + "service_sid": service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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 7371edc08f..f7f506f57a 100644 --- a/twilio/rest/verify/v2/service/entity/__init__.py +++ b/twilio/rest/verify/v2/service/entity/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -63,6 +64,7 @@ def __init__( "service_sid": service_sid, "identity": identity or self.identity, } + self._context: Optional[EntityContext] = None @property @@ -99,6 +101,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the EntityInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EntityInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "EntityInstance": """ Fetch the EntityInstance @@ -117,6 +137,24 @@ async def fetch_async(self) -> "EntityInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EntityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the EntityInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def challenges(self) -> ChallengeList: """ @@ -173,6 +211,20 @@ def __init__(self, version: Version, service_sid: str, identity: str): self._factors: Optional[FactorList] = None self._new_factors: Optional[NewFactorList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the EntityInstance @@ -180,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: @@ -192,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: @@ -204,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: """ @@ -224,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: @@ -294,6 +430,7 @@ def get_instance(self, payload: Dict[str, Any]) -> EntityInstance: :param payload: Payload response from the API """ + return EntityInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -325,13 +462,12 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Entities".format(**self._solution) - def create(self, identity: str) -> EntityInstance: + def _create(self, identity: str) -> tuple: """ - Create the EntityInstance - - :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( @@ -341,21 +477,47 @@ def create(self, identity: str) -> EntityInstance: ) headers = values.of({"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) -> 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( @@ -365,14 +527,41 @@ async def create_async(self, identity: str) -> EntityInstance: ) headers = values.of({"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) -> 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, @@ -423,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, @@ -442,6 +681,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -468,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( @@ -476,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, @@ -500,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, @@ -527,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: """ @@ -542,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: """ @@ -554,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 9ca2e4089b..9940cbf831 100644 --- a/twilio/rest/verify/v2/service/entity/challenge/__init__.py +++ b/twilio/rest/verify/v2/service/entity/challenge/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -39,6 +40,7 @@ class ChallengeStatuses(object): class FactorTypes(object): PUSH = "push" TOTP = "totp" + PASSKEYS = "passkeys" class ListOrders(object): ASC = "asc" @@ -113,6 +115,7 @@ def __init__( "identity": identity, "sid": sid or self.sid, } + self._context: Optional[ChallengeContext] = None @property @@ -150,6 +153,24 @@ async def fetch_async(self) -> "ChallengeInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChallengeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ChallengeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, auth_payload: Union[str, object] = values.unset, @@ -186,6 +207,42 @@ async def update_async( metadata=metadata, ) + def update_with_http_info( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Update the ChallengeInstance with HTTP info + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + auth_payload=auth_payload, + metadata=metadata, + ) + + async def update_with_http_info_async( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ChallengeInstance with HTTP info + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + auth_payload=auth_payload, + metadata=metadata, + ) + @property def notifications(self) -> NotificationList: """ @@ -230,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 @@ -237,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: """ @@ -258,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({}) - 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, + 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, @@ -306,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, @@ -340,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: """ @@ -372,6 +569,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ChallengeInstance: :param payload: Payload response from the API """ + return ChallengeInstance( self._version, payload, @@ -410,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, @@ -418,18 +616,12 @@ def create( details_fields: Union[List[object], object] = values.unset, hidden_details: Union[object, object] = values.unset, auth_payload: Union[str, object] = values.unset, - ) -> ChallengeInstance: + ) -> tuple: """ - Create the ChallengeInstance - - :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( @@ -446,10 +638,43 @@ def create( ) headers = values.of({"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, + 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, @@ -457,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, @@ -465,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. @@ -476,7 +701,38 @@ async def create_async( :param hidden_details: Details provided to give context about the Challenge. Not shown to the end user. It must be a stringified JSON with only strings values eg. `{\\\"ip\\\": \\\"172.168.1.234\\\"}`. Can be up to 1024 characters in length :param auth_payload: Optional payload used to verify the Challenge upon creation. Only used with a Factor of type `totp` to carry the TOTP code that needs to be verified. For `TOTP` this value must be between 3 and 8 characters long. - :returns: The created ChallengeInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + factor_sid=factor_sid, + expiration_date=expiration_date, + details_message=details_message, + details_fields=details_fields, + hidden_details=hidden_details, + auth_payload=auth_payload, + ) + instance = ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + factor_sid: str, + expiration_date: Union[datetime, object] = values.unset, + details_message: Union[str, object] = values.unset, + details_fields: Union[List[object], object] = values.unset, + hidden_details: Union[object, object] = values.unset, + auth_payload: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -493,10 +749,43 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -504,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, @@ -576,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, @@ -601,6 +997,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( factor_sid=factor_sid, @@ -636,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( @@ -647,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, @@ -680,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, @@ -716,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: """ @@ -731,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: """ @@ -743,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 eadf42b81d..4250597da6 100644 --- a/twilio/rest/verify/v2/service/entity/challenge/notification.py +++ b/twilio/rest/verify/v2/service/entity/challenge/notification.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -98,13 +99,12 @@ def __init__( **self._solution ) - def create(self, ttl: Union[int, object] = values.unset) -> NotificationInstance: + def _create(self, ttl: Union[int, object] = values.unset) -> tuple: """ - Create the NotificationInstance - - :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 300. Default is 300. Delivery is attempted until the TTL elapses, even if the device is offline. 0 means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. + Internal helper for create operation - :returns: The created NotificationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -114,10 +114,23 @@ def create(self, ttl: Union[int, object] = values.unset) -> NotificationInstance ) headers = values.of({"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, 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, @@ -126,15 +139,32 @@ def create(self, ttl: Union[int, object] = values.unset) -> NotificationInstance challenge_sid=self._solution["challenge_sid"], ) - async def create_async( + def create_with_http_info( self, ttl: Union[int, object] = values.unset - ) -> NotificationInstance: + ) -> ApiResponse: """ - Asynchronously create the NotificationInstance + Create the NotificationInstance and return response metadata :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 300. Default is 300. Delivery is attempted until the TTL elapses, even if the device is offline. 0 means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. - :returns: The created NotificationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(ttl=ttl) + instance = NotificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + challenge_sid=self._solution["challenge_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ttl: Union[int, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -144,10 +174,25 @@ async def create_async( ) headers = values.of({"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, 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, @@ -156,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 8900fcbfc2..823dd53f69 100644 --- a/twilio/rest/verify/v2/service/entity/factor.py +++ b/twilio/rest/verify/v2/service/entity/factor.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,6 +32,7 @@ class FactorStatuses(object): class FactorTypes(object): PUSH = "push" TOTP = "totp" + PASSKEYS = "passkeys" class TotpAlgorithms(object): SHA1 = "sha1" @@ -88,6 +90,7 @@ def __init__( "identity": identity, "sid": sid or self.sid, } + self._context: Optional[FactorContext] = None @property @@ -125,6 +128,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the FactorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FactorInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "FactorInstance": """ Fetch the FactorInstance @@ -143,6 +164,24 @@ async def fetch_async(self) -> "FactorInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FactorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the FactorInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, auth_payload: Union[str, object] = values.unset, @@ -221,6 +260,84 @@ async def update_async( config_notification_platform=config_notification_platform, ) + def update_with_http_info( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the FactorInstance with HTTP info + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + + async def update_with_http_info_async( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FactorInstance with HTTP info + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -254,6 +371,20 @@ def __init__(self, version: Version, service_sid: str, identity: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the FactorInstance @@ -261,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: @@ -273,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: @@ -285,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: """ @@ -306,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, @@ -331,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, @@ -360,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, @@ -375,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, @@ -386,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. @@ -400,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, @@ -415,13 +704,54 @@ async def update_async( "Config.NotificationPlatform": config_notification_platform, } ) + 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, + 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, @@ -430,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 @@ -448,6 +825,7 @@ def get_instance(self, payload: Dict[str, Any]) -> FactorInstance: :param payload: Payload response from the API """ + return FactorInstance( self._version, payload, @@ -536,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, @@ -555,6 +983,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -581,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( @@ -589,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, @@ -613,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, @@ -640,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: """ @@ -655,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: """ @@ -667,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 c88a945853..79184c0e74 100644 --- a/twilio/rest/verify/v2/service/entity/new_factor.py +++ b/twilio/rest/verify/v2/service/entity/new_factor.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -30,6 +31,7 @@ class FactorStatuses(object): class FactorTypes(object): PUSH = "push" TOTP = "totp" + PASSKEYS = "passkeys" class NotificationPlatforms(object): APN = "apn" @@ -48,6 +50,7 @@ class TotpAlgorithms(object): :ivar entity_sid: The unique SID identifier of the Entity. :ivar identity: Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. :ivar binding: Contains the `factor_type` specific secret and metadata. For push, this is `binding.public_key` and `binding.alg`. For totp, this is `binding.secret` and `binding.uri`. The `binding.uri` property is generated following the [google authenticator key URI format](https://github.com/google/google-authenticator/wiki/Key-Uri-Format), and `Factor.friendly_name` is used for the “accountname” value and `Service.friendly_name` or `Service.totp.issuer` is used for the `issuer` value. The Binding property is ONLY returned upon Factor creation. + :ivar options: :ivar date_created: The date that this Factor was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar date_updated: The date that this Factor was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. @@ -69,6 +72,7 @@ def __init__( self.entity_sid: Optional[str] = payload.get("entity_sid") self.identity: Optional[str] = payload.get("identity") self.binding: Optional[Dict[str, object]] = payload.get("binding") + self.options: Optional[Dict[str, object]] = payload.get("options") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -123,7 +127,7 @@ def __init__(self, version: Version, service_sid: str, identity: str): **self._solution ) - def create( + def _create( self, friendly_name: str, factor_type: "NewFactorInstance.FactorTypes", @@ -141,26 +145,12 @@ def create( config_code_length: Union[int, object] = values.unset, config_alg: Union["NewFactorInstance.TotpAlgorithms", object] = values.unset, metadata: Union[object, object] = values.unset, - ) -> NewFactorInstance: + ) -> tuple: """ - Create the NewFactorInstance - - :param friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. - :param factor_type: - :param binding_alg: The algorithm used when `factor_type` is `push`. Algorithm supported: `ES256` - :param binding_public_key: The Ecdsa public key in PKIX, ASN.1 DER format encoded in Base64. Required when `factor_type` is `push` - :param config_app_id: The ID that uniquely identifies your app in the Google or Apple store, such as `com.example.myapp`. It can be up to 100 characters long. Required when `factor_type` is `push`. - :param config_notification_platform: - :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Must be between 32 and 255 characters long. Required when `factor_type` is `push`. - :param config_sdk_version: The Verify Push SDK version used to configure the factor Required when `factor_type` is `push` - :param binding_secret: The shared secret for TOTP factors encoded in Base32. This can be provided when creating the Factor, otherwise it will be generated. Used when `factor_type` is `totp` - :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. The default value is defined at the service level in the property `totp.time_step`. Defaults to 30 seconds if not configured. Used when `factor_type` is `totp` - :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. The default value is defined at the service level in the property `totp.skew`. If not configured defaults to 1. Used when `factor_type` is `totp` - :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. The default value is defined at the service level in the property `totp.code_length`. If not configured defaults to 6. Used when `factor_type` is `totp` - :param config_alg: - :param metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + Internal helper for create operation - :returns: The created NewFactorInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -183,10 +173,69 @@ def create( ) headers = values.of({"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, + 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, @@ -194,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", @@ -212,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: @@ -231,7 +280,56 @@ async def create_async( :param config_alg: :param metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. - :returns: The created NewFactorInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + factor_type=factor_type, + binding_alg=binding_alg, + binding_public_key=binding_public_key, + config_app_id=config_app_id, + config_notification_platform=config_notification_platform, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + binding_secret=binding_secret, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + metadata=metadata, + ) + instance = NewFactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + factor_type: "NewFactorInstance.FactorTypes", + binding_alg: Union[str, object] = values.unset, + binding_public_key: Union[str, object] = values.unset, + config_app_id: Union[str, object] = values.unset, + config_notification_platform: Union[ + "NewFactorInstance.NotificationPlatforms", object + ] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + binding_secret: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["NewFactorInstance.TotpAlgorithms", object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -254,10 +352,69 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -265,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 b841770331..43920cc5b9 100644 --- a/twilio/rest/verify/v2/service/messaging_configuration.py +++ b/twilio/rest/verify/v2/service/messaging_configuration.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -58,6 +59,7 @@ def __init__( "service_sid": service_sid, "country": country or self.country, } + self._context: Optional[MessagingConfigurationContext] = None @property @@ -94,6 +96,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the MessagingConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessagingConfigurationInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "MessagingConfigurationInstance": """ Fetch the MessagingConfigurationInstance @@ -112,6 +132,24 @@ async def fetch_async(self) -> "MessagingConfigurationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessagingConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the MessagingConfigurationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, messaging_service_sid: str) -> "MessagingConfigurationInstance": """ Update the MessagingConfigurationInstance @@ -138,6 +176,32 @@ async def update_async( messaging_service_sid=messaging_service_sid, ) + def update_with_http_info(self, messaging_service_sid: str) -> ApiResponse: + """ + Update the MessagingConfigurationInstance with HTTP info + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + messaging_service_sid=messaging_service_sid, + ) + + async def update_with_http_info_async( + self, messaging_service_sid: str + ) -> ApiResponse: + """ + Asynchronous coroutine to update the MessagingConfigurationInstance with HTTP info + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + messaging_service_sid=messaging_service_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -169,6 +233,20 @@ def __init__(self, version: Version, service_sid: str, country: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the MessagingConfigurationInstance @@ -176,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: @@ -188,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: @@ -200,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: """ @@ -220,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, @@ -233,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/messaging/api/service-resource) to be used to send SMS to the country of this configuration. - :returns: The updated MessagingConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, messaging_service_sid: str) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "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, @@ -260,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/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" - 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, 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, @@ -289,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 @@ -307,6 +535,7 @@ def get_instance(self, payload: Dict[str, Any]) -> MessagingConfigurationInstanc :param payload: Payload response from the API """ + return MessagingConfigurationInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -340,16 +569,12 @@ def __init__(self, version: Version, service_sid: str): **self._solution ) - def create( - self, country: str, messaging_service_sid: str - ) -> MessagingConfigurationInstance: + def _create(self, country: str, messaging_service_sid: str) -> tuple: """ - Create the MessagingConfigurationInstance + Internal helper for create operation - :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. - - :returns: The created MessagingConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -360,24 +585,57 @@ def create( ) headers = values.of({"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, country: str, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Create the MessagingConfigurationInstance + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The created MessagingConfigurationInstance + """ + payload, _, _ = self._create( + country=country, messaging_service_sid=messaging_service_sid + ) return MessagingConfigurationInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, country: str, messaging_service_sid: str - ) -> MessagingConfigurationInstance: + ) -> ApiResponse: """ - Asynchronously create the MessagingConfigurationInstance + Create the MessagingConfigurationInstance and return response metadata :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. - :returns: The created MessagingConfigurationInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + country=country, messaging_service_sid=messaging_service_sid + ) + instance = MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, country: str, messaging_service_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -388,14 +646,51 @@ async def create_async( ) headers = values.of({"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, country: str, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Asynchronously create the MessagingConfigurationInstance + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The created MessagingConfigurationInstance + """ + payload, _, _ = await self._create_async( + country=country, messaging_service_sid=messaging_service_sid + ) return MessagingConfigurationInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, country: str, messaging_service_sid: str + ) -> ApiResponse: + """ + Asynchronously create the MessagingConfigurationInstance and return response metadata + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + country=country, messaging_service_sid=messaging_service_sid + ) + instance = MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -446,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, @@ -465,6 +810,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -491,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( @@ -499,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, @@ -523,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, @@ -550,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, self._solution) + return MessagingConfigurationPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagingConfigurationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = MessagingConfigurationPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with MessagingConfigurationPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = MessagingConfigurationPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MessagingConfigurationPage: """ @@ -565,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: """ @@ -577,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 bdd165858a..e01a326d9e 100644 --- a/twilio/rest/verify/v2/service/rate_limit/__init__.py +++ b/twilio/rest/verify/v2/service/rate_limit/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -63,6 +64,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[RateLimitContext] = None @property @@ -99,6 +101,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RateLimitInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RateLimitInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RateLimitInstance": """ Fetch the RateLimitInstance @@ -117,6 +137,24 @@ async def fetch_async(self) -> "RateLimitInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RateLimitInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RateLimitInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, description: Union[str, object] = values.unset ) -> "RateLimitInstance": @@ -145,6 +183,34 @@ async def update_async( description=description, ) + def update_with_http_info( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the RateLimitInstance with HTTP info + + :param description: Description of this Rate Limit + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + description=description, + ) + + async def update_with_http_info_async( + self, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RateLimitInstance with HTTP info + + :param description: Description of this Rate Limit + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + description=description, + ) + @property def buckets(self) -> BucketList: """ @@ -183,6 +249,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): self._buckets: Optional[BucketList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RateLimitInstance @@ -190,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: @@ -202,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: @@ -214,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: """ @@ -234,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, @@ -247,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, @@ -276,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" - 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, 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, @@ -305,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: """ @@ -336,6 +566,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RateLimitInstance: :param payload: Payload response from the API """ + return RateLimitInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -367,16 +598,14 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/RateLimits".format(**self._solution) - def create( + def _create( self, unique_name: str, description: Union[str, object] = values.unset - ) -> RateLimitInstance: + ) -> tuple: """ - Create the RateLimitInstance - - :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** - :param description: Description of this Rate Limit + Internal helper for create operation - :returns: The created RateLimitInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -387,24 +616,57 @@ def create( ) headers = values.of({"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, unique_name: str, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Create the RateLimitInstance + + :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** + :param description: Description of this Rate Limit + + :returns: The created RateLimitInstance + """ + payload, _, _ = self._create(unique_name=unique_name, description=description) return RateLimitInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, unique_name: str, description: Union[str, object] = values.unset - ) -> RateLimitInstance: + ) -> ApiResponse: """ - Asynchronously create the RateLimitInstance + Create the RateLimitInstance and return response metadata :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** :param description: Description of this Rate Limit - :returns: The created RateLimitInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, description=description + ) + instance = RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -415,14 +677,51 @@ async def create_async( ) headers = values.of({"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, unique_name: str, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Asynchronously create the RateLimitInstance + + :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** + :param description: Description of this Rate Limit + + :returns: The created RateLimitInstance + """ + payload, _, _ = await self._create_async( + unique_name=unique_name, description=description + ) return RateLimitInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the RateLimitInstance and return response metadata + + :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** + :param description: Description of this Rate Limit + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + unique_name=unique_name, description=description + ) + instance = RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -473,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, @@ -492,6 +841,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -518,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( @@ -526,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, @@ -550,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, @@ -577,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: """ @@ -592,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: """ @@ -604,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 dee84901e5..9b47a70c3c 100644 --- a/twilio/rest/verify/v2/service/rate_limit/bucket.py +++ b/twilio/rest/verify/v2/service/rate_limit/bucket.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -64,6 +65,7 @@ def __init__( "rate_limit_sid": rate_limit_sid, "sid": sid or self.sid, } + self._context: Optional[BucketContext] = None @property @@ -101,6 +103,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the BucketInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BucketInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "BucketInstance": """ Fetch the BucketInstance @@ -119,6 +139,24 @@ async def fetch_async(self) -> "BucketInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BucketInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BucketInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, max: Union[int, object] = values.unset, @@ -155,6 +193,42 @@ async def update_async( interval=interval, ) + def update_with_http_info( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Update the BucketInstance with HTTP info + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + max=max, + interval=interval, + ) + + async def update_with_http_info_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BucketInstance with HTTP info + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + max=max, + interval=interval, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -192,6 +266,20 @@ def __init__( ) ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the BucketInstance @@ -199,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: @@ -211,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: @@ -223,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: """ @@ -244,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 - - :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 update operation - :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, @@ -292,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({}) + + 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, + 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, @@ -326,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 @@ -344,6 +598,7 @@ def get_instance(self, payload: Dict[str, Any]) -> BucketInstance: :param payload: Payload response from the API """ + return BucketInstance( self._version, payload, @@ -384,14 +639,12 @@ def __init__(self, version: Version, service_sid: str, rate_limit_sid: str): ) ) - def create(self, max: int, interval: int) -> BucketInstance: + def _create(self, max: int, interval: int) -> tuple: """ - Create the BucketInstance - - :param max: Maximum number of requests permitted in during the interval. - :param interval: Number of seconds that the rate limit will be enforced over. + Internal helper for create operation - :returns: The created BucketInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -402,10 +655,24 @@ def create(self, max: int, interval: int) -> BucketInstance: ) headers = values.of({"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, 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, @@ -413,14 +680,30 @@ def create(self, max: int, interval: int) -> BucketInstance: rate_limit_sid=self._solution["rate_limit_sid"], ) - async def create_async(self, max: int, interval: int) -> BucketInstance: + def create_with_http_info(self, max: int, interval: int) -> ApiResponse: """ - Asynchronously create the BucketInstance + Create the BucketInstance and return response metadata :param max: Maximum number of requests permitted in during the interval. :param interval: Number of seconds that the rate limit will be enforced over. - :returns: The created BucketInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(max=max, interval=interval) + instance = BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, max: int, interval: int) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -431,10 +714,24 @@ async def create_async(self, max: int, interval: int) -> BucketInstance: ) headers = values.of({"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, 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, @@ -442,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, @@ -492,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, @@ -511,6 +878,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -537,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( @@ -545,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, @@ -569,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, @@ -596,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: """ @@ -611,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: """ @@ -623,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 c8deef535b..88ae5cb750 100644 --- a/twilio/rest/verify/v2/service/verification.py +++ b/twilio/rest/verify/v2/service/verification.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -91,6 +92,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[VerificationContext] = None @property @@ -127,6 +129,24 @@ async def fetch_async(self) -> "VerificationInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VerificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VerificationInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, status: "VerificationInstance.Status") -> "VerificationInstance": """ Update the VerificationInstance @@ -153,6 +173,34 @@ async def update_async( status=status, ) + def update_with_http_info( + self, status: "VerificationInstance.Status" + ) -> ApiResponse: + """ + Update the VerificationInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: "VerificationInstance.Status" + ) -> ApiResponse: + """ + Asynchronous coroutine to update the VerificationInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -184,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 @@ -191,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: """ @@ -211,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, @@ -224,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" + + 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: "VerificationInstance.Status") -> VerificationInstance: + """ + Update the VerificationInstance + + :param status: + + :returns: The updated VerificationInstance + """ + payload, _, _ = self._update(status=status) return VerificationInstance( self._version, payload, @@ -251,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" - 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: "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, @@ -280,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 @@ -308,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, @@ -325,31 +489,15 @@ def create( 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: + ) -> tuple: """ - Create the VerificationInstance + Internal helper for create operation - :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). - :param channel: The verification method to use. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, `sna` or `auto`. - :param custom_friendly_name: A custom user defined friendly name that overwrites the existing one in the verification message - :param custom_message: The text of a custom message to use for the verification. - :param send_digits: The digits to send after a phone call is answered, for example, to dial an extension. For more information, see the Programmable Voice documentation of [sendDigits](https://www.twilio.com/docs/voice/twiml/number#attributes-sendDigits). - :param locale: Locale will automatically resolve based on phone number country code for SMS, WhatsApp, and call channel verifications. It will fallback to English or the template’s default translation if the selected translation is not available. This parameter will override the automatic locale resolution. [See supported languages and more information here](https://www.twilio.com/docs/verify/supported-languages). - :param custom_code: A pre-generated code to use for verification. The code can be between 4 and 10 characters, inclusive. - :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. - :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. - :param rate_limits: The custom key-value pairs of Programmable Rate Limits. Keys correspond to `unique_name` fields defined when [creating your Rate Limit](https://www.twilio.com/docs/verify/api/service-rate-limits). Associated value pairs represent values in the request that you are rate limiting on. You may include multiple Rate Limit values in each request. - :param channel_configuration: [`email`](https://www.twilio.com/docs/verify/email) channel configuration in json format. The fields 'from' and 'from_name' are optional but if included the 'from' field must have a valid email address. - :param app_hash: Your [App Hash](https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string) to be appended at the end of your verification SMS body. Applies only to SMS. Example SMS body: `<#> Your AppName verification code is: 1234 He42w354ol9`. - :param template_sid: The message [template](https://www.twilio.com/docs/verify/api/templates). If provided, will override the default template for the Service. SMS and Voice channels only. - :param template_custom_substitutions: A stringified JSON object in which the keys are the template's special variables and the values are the variables substitutions. - :param device_ip: Strongly encouraged if using the auto channel. The IP address of the client's device. If provided, it has to be a valid IPv4 or IPv6 address. - :param risk_check: - :param tags: A string containing a JSON map of key value pairs of tags to be recorded as metadata for the message. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. - - :returns: The created VerificationInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -369,21 +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"}) - 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, + 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, @@ -400,16 +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, + enable_sna_client_token: Union[bool, object] = values.unset, risk_check: Union["VerificationInstance.RiskCheck", object] = values.unset, tags: Union[str, object] = values.unset, - ) -> VerificationInstance: + ) -> ApiResponse: """ - Asynchronously create the VerificationInstance + Create the VerificationInstance and return response metadata :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). :param channel: The verification method to use. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, `sna` or `auto`. :param custom_friendly_name: A custom user defined friendly name that overwrites the existing one in the verification message - :param custom_message: The text of a custom message to use for the verification. + :param custom_message: The text of a custom message to use for the verification [DEPRECATED]. :param send_digits: The digits to send after a phone call is answered, for example, to dial an extension. For more information, see the Programmable Voice documentation of [sendDigits](https://www.twilio.com/docs/voice/twiml/number#attributes-sendDigits). :param locale: Locale will automatically resolve based on phone number country code for SMS, WhatsApp, and call channel verifications. It will fallback to English or the template’s default translation if the selected translation is not available. This parameter will override the automatic locale resolution. [See supported languages and more information here](https://www.twilio.com/docs/verify/supported-languages). :param custom_code: A pre-generated code to use for verification. The code can be between 4 and 10 characters, inclusive. @@ -421,10 +642,63 @@ 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 object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. + :param tags: A string containing a JSON map of key value pairs of tags to be recorded as metadata for the message. The tags will also be included as part of the verification and message status event type payloads. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. **This value should not contain PII.** + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + to=to, + channel=channel, + custom_friendly_name=custom_friendly_name, + custom_message=custom_message, + send_digits=send_digits, + locale=locale, + custom_code=custom_code, + amount=amount, + payee=payee, + rate_limits=rate_limits, + channel_configuration=channel_configuration, + app_hash=app_hash, + template_sid=template_sid, + template_custom_substitutions=template_custom_substitutions, + device_ip=device_ip, + enable_sna_client_token=enable_sna_client_token, + risk_check=risk_check, + tags=tags, + ) + instance = VerificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - :returns: The created VerificationInstance + async def _create_async( + self, + to: str, + channel: str, + custom_friendly_name: Union[str, object] = values.unset, + custom_message: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + custom_code: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + rate_limits: Union[object, object] = values.unset, + channel_configuration: Union[object, object] = values.unset, + app_hash: Union[str, object] = values.unset, + template_sid: Union[str, object] = values.unset, + template_custom_substitutions: Union[str, object] = values.unset, + device_ip: Union[str, object] = values.unset, + enable_sna_client_token: Union[bool, object] = values.unset, + risk_check: Union["VerificationInstance.RiskCheck", object] = values.unset, + tags: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -444,20 +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"}) - 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, + 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 af216a39f6..b80c8d6d46 100644 --- a/twilio/rest/verify/v2/service/verification_check.py +++ b/twilio/rest/verify/v2/service/verification_check.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -101,24 +102,20 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/VerificationCheck".format(**self._solution) - def create( + def _create( self, code: Union[str, object] = values.unset, to: Union[str, object] = values.unset, verification_sid: Union[str, object] = values.unset, amount: Union[str, object] = values.unset, payee: Union[str, object] = values.unset, - ) -> VerificationCheckInstance: + sna_client_token: Union[str, object] = values.unset, + ) -> tuple: """ - Create the VerificationCheckInstance - - :param code: The 4-10 character string being verified. - :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). - :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. - :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. - :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + Internal helper for create operation - :returns: The created VerificationCheckInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -128,36 +125,100 @@ 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( + 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, + to: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + sna_client_token: Union[str, object] = values.unset, + ) -> VerificationCheckInstance: + """ + Create the VerificationCheckInstance + + :param code: The 4-10 character string being verified. + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. + + :returns: The created VerificationCheckInstance + """ + payload, _, _ = self._create( + code=code, + to=to, + verification_sid=verification_sid, + amount=amount, + payee=payee, + sna_client_token=sna_client_token, + ) return VerificationCheckInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, code: Union[str, object] = values.unset, to: Union[str, object] = values.unset, verification_sid: Union[str, object] = values.unset, amount: Union[str, object] = values.unset, payee: Union[str, object] = values.unset, - ) -> VerificationCheckInstance: + sna_client_token: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Asynchronously create the VerificationCheckInstance + Create the VerificationCheckInstance and return response metadata :param code: The 4-10 character string being verified. :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). :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 + :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( @@ -167,18 +228,86 @@ async def create_async( "VerificationSid": verification_sid, "Amount": amount, "Payee": payee, + "SnaClientToken": sna_client_token, } ) headers = values.of({"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, + code: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + sna_client_token: Union[str, object] = values.unset, + ) -> VerificationCheckInstance: + """ + Asynchronously create the VerificationCheckInstance + + :param code: The 4-10 character string being verified. + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. + + :returns: The created VerificationCheckInstance + """ + payload, _, _ = await self._create_async( + code=code, + to=to, + verification_sid=verification_sid, + amount=amount, + payee=payee, + sna_client_token=sna_client_token, + ) return VerificationCheckInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + code: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + sna_client_token: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the VerificationCheckInstance and return response metadata + + :param code: The 4-10 character string being verified. + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + code=code, + to=to, + verification_sid=verification_sid, + amount=amount, + payee=payee, + sna_client_token=sna_client_token, + ) + instance = VerificationCheckInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/verify/v2/service/webhook.py b/twilio/rest/verify/v2/service/webhook.py index 67ffced265..2e59c8c4bb 100644 --- a/twilio/rest/verify/v2/service/webhook.py +++ b/twilio/rest/verify/v2/service/webhook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -83,6 +84,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[WebhookContext] = None @property @@ -119,6 +121,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "WebhookInstance": """ Fetch the WebhookInstance @@ -137,13 +157,31 @@ async def fetch_async(self) -> "WebhookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the WebhookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, event_types: Union[List[str], object] = values.unset, webhook_url: Union[str, object] = values.unset, status: Union["WebhookInstance.Status", object] = values.unset, - version: Union["WebhookInstance.Version", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, ) -> "WebhookInstance": """ Update the WebhookInstance @@ -152,7 +190,7 @@ def update( :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` :param webhook_url: The URL associated with this Webhook. :param status: - :param version: + :param resource_version: :returns: The updated WebhookInstance """ @@ -161,7 +199,7 @@ def update( event_types=event_types, webhook_url=webhook_url, status=status, - version=version, + resource_version=resource_version, ) async def update_async( @@ -170,7 +208,7 @@ async def update_async( event_types: Union[List[str], object] = values.unset, webhook_url: Union[str, object] = values.unset, status: Union["WebhookInstance.Status", object] = values.unset, - version: Union["WebhookInstance.Version", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, ) -> "WebhookInstance": """ Asynchronous coroutine to update the WebhookInstance @@ -179,7 +217,7 @@ async def update_async( :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` :param webhook_url: The URL associated with this Webhook. :param status: - :param version: + :param resource_version: :returns: The updated WebhookInstance """ @@ -188,7 +226,61 @@ async def update_async( event_types=event_types, webhook_url=webhook_url, status=status, - version=version, + resource_version=resource_version, + ) + + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: + """ + Update the WebhookInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the WebhookInstance with HTTP info + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, ) def __repr__(self) -> str: @@ -220,6 +312,20 @@ def __init__(self, version: Version, service_sid: str, sid: str): } self._uri = "/Services/{service_sid}/Webhooks/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the WebhookInstance @@ -227,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: @@ -239,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: @@ -251,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: """ @@ -271,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, @@ -326,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({}) - 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, + 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, @@ -368,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 @@ -386,6 +694,7 @@ def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: :param payload: Payload response from the API """ + return WebhookInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -417,24 +726,19 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Webhooks".format(**self._solution) - def create( + def _create( self, friendly_name: str, event_types: List[str], webhook_url: str, status: Union["WebhookInstance.Status", object] = values.unset, - version: Union["WebhookInstance.Version", object] = values.unset, - ) -> WebhookInstance: + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> tuple: """ - Create the WebhookInstance + Internal helper for create operation - :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** - :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` - :param webhook_url: The URL associated with this Webhook. - :param status: - :param version: - - :returns: The created WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -443,37 +747,93 @@ def create( "EventTypes": serialize.map(event_types, lambda e: e), "WebhookUrl": webhook_url, "Status": status, - "Version": version, + "Version": resource_version, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: The created WebhookInstance + """ + payload, _, _ = self._create( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) return WebhookInstance( self._version, payload, service_sid=self._solution["service_sid"] ) - async def create_async( + def create_with_http_info( self, friendly_name: str, event_types: List[str], webhook_url: str, status: Union["WebhookInstance.Status", object] = values.unset, - version: Union["WebhookInstance.Version", object] = values.unset, - ) -> WebhookInstance: + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: """ - Asynchronously create the WebhookInstance + Create the WebhookInstance and return response metadata :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` :param webhook_url: The URL associated with this Webhook. :param status: - :param version: + :param resource_version: - :returns: The created WebhookInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + instance = WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -482,19 +842,80 @@ async def create_async( "EventTypes": serialize.map(event_types, lambda e: e), "WebhookUrl": webhook_url, "Status": status, - "Version": version, + "Version": resource_version, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: The created WebhookInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) return WebhookInstance( self._version, payload, service_sid=self._solution["service_sid"] ) + async def create_with_http_info_async( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the WebhookInstance and return response metadata + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param resource_version: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, + ) + instance = WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -545,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, @@ -564,6 +1035,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -590,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( @@ -598,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, @@ -622,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, @@ -649,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: """ @@ -664,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: """ @@ -676,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 b9968eec87..4dfecf8f57 100644 --- a/twilio/rest/verify/v2/template.py +++ b/twilio/rest/verify/v2/template.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def get_instance(self, payload: Dict[str, Any]) -> TemplateInstance: :param payload: Payload response from the API """ + return TemplateInstance(self._version, payload) def __repr__(self) -> str: @@ -137,6 +139,62 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams TemplateInstance and returns headers from first page + + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams TemplateInstance and returns headers from first page + + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, friendly_name: Union[str, object] = values.unset, @@ -158,6 +216,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -187,6 +246,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -196,6 +256,62 @@ async def list_async( ) ] + def list_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists TemplateInstance and returns headers from first page + + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists TemplateInstance and returns headers from first page + + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, friendly_name: Union[str, object] = values.unset, @@ -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( @@ -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 2c1f914d32..4704ee828a 100644 --- a/twilio/rest/verify/v2/verification_attempt.py +++ b/twilio/rest/verify/v2/verification_attempt.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -29,6 +30,7 @@ class Channels(object): CALL = "call" EMAIL = "email" WHATSAPP = "whatsapp" + RBM = "rbm" class ConversionStatus(object): CONVERTED = "converted" @@ -76,6 +78,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[VerificationAttemptContext] = None @property @@ -111,6 +114,24 @@ async def fetch_async(self) -> "VerificationAttemptInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VerificationAttemptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VerificationAttemptInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -138,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 @@ -145,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: """ @@ -164,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: """ @@ -194,6 +267,7 @@ def get_instance(self, payload: Dict[str, Any]) -> VerificationAttemptInstance: :param payload: Payload response from the API """ + return VerificationAttemptInstance(self._version, payload) def __repr__(self) -> str: @@ -243,7 +317,7 @@ def stream( :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. :param str country: Filter used to query Verification Attempts sent to the specified destination country. - :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. @@ -296,7 +370,7 @@ async def stream_async( :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. :param str country: Filter used to query Verification Attempts sent to the specified destination country. - :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. @@ -324,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, @@ -348,7 +526,7 @@ def list( :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. :param str country: Filter used to query Verification Attempts sent to the specified destination country. - :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. @@ -361,6 +539,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created_after=date_created_after, @@ -400,7 +579,7 @@ async def list_async( :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. :param str country: Filter used to query Verification Attempts sent to the specified destination country. - :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. @@ -413,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( @@ -429,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, @@ -453,7 +735,7 @@ def page( :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param channel_data_to: Destination of a verification. It is phone number in E.164 format. :param country: Filter used to query Verification Attempts sent to the specified destination country. - :param channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param channel: Filter used to query Verification Attempts by communication channel. :param verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. :param verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. :param status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. @@ -479,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( @@ -506,7 +794,7 @@ async def page_async( :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param channel_data_to: Destination of a verification. It is phone number in E.164 format. :param country: Filter used to query Verification Attempts sent to the specified destination country. - :param channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param channel: Filter used to query Verification Attempts by communication channel. :param verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. :param verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. :param status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. @@ -532,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 1f2d3d3955..0f226478b5 100644 --- a/twilio/rest/verify/v2/verification_attempts_summary.py +++ b/twilio/rest/verify/v2/verification_attempts_summary.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -28,6 +29,7 @@ class Channels(object): CALL = "call" EMAIL = "email" WHATSAPP = "whatsapp" + RBM = "rbm" """ :ivar total_attempts: Total of attempts made according to the provided filters @@ -49,8 +51,8 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.total_unconverted: Optional[int] = deserialize.integer( payload.get("total_unconverted") ) - self.conversion_rate_percentage: Optional[float] = deserialize.decimal( - payload.get("conversion_rate_percentage") + self.conversion_rate_percentage: Optional[str] = payload.get( + "conversion_rate_percentage" ) self.url: Optional[str] = payload.get("url") @@ -88,7 +90,7 @@ def fetch( :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. - :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. :returns: The fetched VerificationAttemptsSummaryInstance @@ -120,7 +122,7 @@ async def fetch_async( :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. - :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. :returns: The fetched VerificationAttemptsSummaryInstance @@ -134,6 +136,70 @@ async def fetch_async( destination_prefix=destination_prefix, ) + def fetch_with_http_info( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Fetch the VerificationAttemptsSummaryInstance with HTTP info + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + verify_service_sid=verify_service_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + country=country, + channel=channel, + destination_prefix=destination_prefix, + ) + + async def fetch_with_http_info_async( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the VerificationAttemptsSummaryInstance with HTTP info + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + verify_service_sid=verify_service_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + country=country, + channel=channel, + destination_prefix=destination_prefix, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -156,7 +222,7 @@ def __init__(self, version: Version): self._uri = "/Attempts/Summary" - def fetch( + def _fetch( self, verify_service_sid: Union[str, object] = values.unset, date_created_after: Union[datetime, object] = values.unset, @@ -166,21 +232,15 @@ def fetch( "VerificationAttemptsSummaryInstance.Channels", object ] = values.unset, destination_prefix: Union[str, object] = values.unset, - ) -> VerificationAttemptsSummaryInstance: + ) -> tuple: """ - Fetch the VerificationAttemptsSummaryInstance + Internal helper for fetch operation - :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. - :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. - :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. - :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. - :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` - :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. - - :returns: The fetched VerificationAttemptsSummaryInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "VerifyServiceSid": verify_service_sid, "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), @@ -191,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, @@ -208,21 +305,52 @@ async def fetch_async( "VerificationAttemptsSummaryInstance.Channels", object ] = values.unset, destination_prefix: Union[str, object] = values.unset, - ) -> VerificationAttemptsSummaryInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the VerificationAttemptsSummaryInstance + Fetch the VerificationAttemptsSummaryInstance and return response metadata :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. - :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. - :returns: The fetched VerificationAttemptsSummaryInstance + :returns: ApiResponse with instance, status code, and headers """ + payload, status_code, headers = self._fetch( + verify_service_sid=verify_service_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + country=country, + channel=channel, + destination_prefix=destination_prefix, + ) + instance = VerificationAttemptsSummaryInstance( + self._version, + payload, + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - 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), @@ -233,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 diff --git a/twilio/rest/video/v1/composition.py b/twilio/rest/video/v1/composition.py index 8add1e74e5..47bb8a9641 100644 --- a/twilio/rest/video/v1/composition.py +++ b/twilio/rest/video/v1/composition.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -101,6 +102,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CompositionContext] = None @property @@ -136,6 +138,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CompositionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CompositionInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CompositionInstance": """ Fetch the CompositionInstance @@ -154,6 +174,24 @@ async def fetch_async(self) -> "CompositionInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CompositionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CompositionInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -181,6 +219,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Compositions/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CompositionInstance @@ -188,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: @@ -200,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: @@ -212,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: """ @@ -231,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: """ @@ -261,6 +395,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CompositionInstance: :param payload: Payload response from the API """ + return CompositionInstance(self._version, payload) def __repr__(self) -> str: @@ -285,7 +420,7 @@ def __init__(self, version: Version): self._uri = "/Compositions" - def create( + def _create( self, room_sid: str, video_layout: Union[object, object] = values.unset, @@ -296,21 +431,12 @@ def create( status_callback: Union[str, object] = values.unset, status_callback_method: Union[str, object] = values.unset, trim: Union[bool, object] = values.unset, - ) -> CompositionInstance: + ) -> tuple: """ - Create the CompositionInstance + Internal helper for create operation - :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. - :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request - :param audio_sources: An array of track names from the same group room to merge into the new composition. Can include zero or more track names. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` includes `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request - :param audio_sources_excluded: An array of track names to exclude. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. - :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. - :param format: - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. - :param trim: Whether to clip the intervals where there is no active media in the composition. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. - - :returns: The created CompositionInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -330,13 +456,15 @@ def create( ) headers = values.of({"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 CompositionInstance(self._version, payload) - - async def create_async( + def create( self, room_sid: str, video_layout: Union[object, object] = values.unset, @@ -349,7 +477,7 @@ async def create_async( trim: Union[bool, object] = values.unset, ) -> CompositionInstance: """ - Asynchronously create the CompositionInstance + Create the CompositionInstance :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request @@ -363,6 +491,78 @@ async def create_async( :returns: The created CompositionInstance """ + payload, _, _ = self._create( + room_sid=room_sid, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + return CompositionInstance(self._version, payload) + + def create_with_http_info( + self, + room_sid: str, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the CompositionInstance and return response metadata + + :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. + :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources: An array of track names from the same group room to merge into the new composition. Can include zero or more track names. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` includes `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources_excluded: An array of track names to exclude. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the composition. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + room_sid=room_sid, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + instance = CompositionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + room_sid: str, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -381,12 +581,95 @@ async def create_async( ) headers = values.of({"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, + room_sid: str, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> CompositionInstance: + """ + Asynchronously create the CompositionInstance + + :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. + :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources: An array of track names from the same group room to merge into the new composition. Can include zero or more track names. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` includes `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources_excluded: An array of track names to exclude. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the composition. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: The created CompositionInstance + """ + payload, _, _ = await self._create_async( + room_sid=room_sid, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) return CompositionInstance(self._version, payload) + async def create_with_http_info_async( + self, + room_sid: str, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CompositionInstance and return response metadata + + :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. + :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources: An array of track names from the same group room to merge into the new composition. Can include zero or more track names. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` includes `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources_excluded: An array of track names to exclude. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the composition. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + room_sid=room_sid, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + instance = CompositionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, status: Union["CompositionInstance.Status", object] = values.unset, @@ -465,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, @@ -492,6 +851,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -530,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( @@ -542,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, @@ -578,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( @@ -617,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 0f833f793f..16e7cb6f4a 100644 --- a/twilio/rest/video/v1/composition_hook.py +++ b/twilio/rest/video/v1/composition_hook.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -78,6 +79,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CompositionHookContext] = None @property @@ -113,6 +115,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CompositionHookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CompositionHookInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CompositionHookInstance": """ Fetch the CompositionHookInstance @@ -131,6 +151,24 @@ async def fetch_async(self) -> "CompositionHookInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CompositionHookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CompositionHookInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: str, @@ -215,6 +253,90 @@ async def update_async( status_callback_method=status_callback_method, ) + def update_with_http_info( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the CompositionHookInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + + async def update_with_http_info_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the CompositionHookInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -242,6 +364,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/CompositionHooks/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CompositionHookInstance @@ -249,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: @@ -261,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: @@ -273,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: """ @@ -292,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, @@ -316,23 +534,14 @@ 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, @@ -349,18 +558,62 @@ def update( "StatusCallbackMethod": status_callback_method, } ) + 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: 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, @@ -372,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. @@ -387,8 +640,45 @@ 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, @@ -405,23 +695,113 @@ async def update_async( "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) @@ -434,6 +814,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CompositionHookInstance: :param payload: Payload response from the API """ + return CompositionHookInstance(self._version, payload) def __repr__(self) -> str: @@ -458,7 +839,7 @@ def __init__(self, version: Version): self._uri = "/CompositionHooks" - def create( + def _create( self, friendly_name: str, enabled: Union[bool, object] = values.unset, @@ -470,22 +851,12 @@ def create( status_callback: Union[str, object] = values.unset, status_callback_method: Union[str, object] = values.unset, trim: Union[bool, object] = values.unset, - ) -> CompositionHookInstance: + ) -> tuple: """ - Create the CompositionHookInstance - - :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. - :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. - :param video_layout: An object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. - :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. - :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. - :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. - :param format: - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. - :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. - :param trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + Internal helper for create operation - :returns: The created CompositionHookInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -506,13 +877,15 @@ def create( ) headers = values.of({"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 CompositionHookInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: str, enabled: Union[bool, object] = values.unset, @@ -526,7 +899,7 @@ async def create_async( trim: Union[bool, object] = values.unset, ) -> CompositionHookInstance: """ - Asynchronously create the CompositionHookInstance + Create the CompositionHookInstance :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. @@ -541,6 +914,83 @@ async def create_async( :returns: The created CompositionHookInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + return CompositionHookInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the CompositionHookInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. + :param video_layout: An object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + instance = CompositionHookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -560,12 +1010,101 @@ async def create_async( ) headers = values.of({"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, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> CompositionHookInstance: + """ + Asynchronously create the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. + :param video_layout: An object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: The created CompositionHookInstance + """ + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) return CompositionHookInstance(self._version, payload) + async def create_with_http_info_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CompositionHookInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. + :param video_layout: An object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + resolution=resolution, + format=format, + status_callback=status_callback, + status_callback_method=status_callback_method, + trim=trim, + ) + instance = CompositionHookInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, enabled: Union[bool, object] = values.unset, @@ -644,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, @@ -671,6 +1286,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( enabled=enabled, @@ -709,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( @@ -721,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, @@ -757,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( @@ -796,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 366ec727cf..ec04358b3d 100644 --- a/twilio/rest/video/v1/composition_settings.py +++ b/twilio/rest/video/v1/composition_settings.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -120,6 +121,66 @@ async def create_async( encryption_enabled=encryption_enabled, ) + def create_with_http_info( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the CompositionSettingsInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + async def create_with_http_info_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the CompositionSettingsInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + def fetch(self) -> "CompositionSettingsInstance": """ Fetch the CompositionSettingsInstance @@ -138,6 +199,24 @@ async def fetch_async(self) -> "CompositionSettingsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CompositionSettingsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CompositionSettingsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -160,6 +239,42 @@ def __init__(self, version: Version): self._uri = "/CompositionSettings/Default" + def _create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "AwsCredentialsSid": aws_credentials_sid, + "EncryptionKeySid": encryption_key_sid, + "AwsS3Url": aws_s3_url, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, friendly_name: str, @@ -181,6 +296,64 @@ def create( :returns: The created CompositionSettingsInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + return CompositionSettingsInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the CompositionSettingsInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + instance = CompositionSettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "FriendlyName": friendly_name, @@ -191,10 +364,15 @@ def create( "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), } ) + headers = values.of({}) - payload = self._version.create(method="POST", uri=self._uri, data=data) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CompositionSettingsInstance(self._version, payload) + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) async def create_async( self, @@ -217,22 +395,63 @@ async def create_async( :returns: The created CompositionSettingsInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "AwsCredentialsSid": aws_credentials_sid, - "EncryptionKeySid": encryption_key_sid, - "AwsS3Url": aws_s3_url, - "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), - "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, ) + return CompositionSettingsInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data + async def create_with_http_info_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the CompositionSettingsInstance and return response metadata + + :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: """ @@ -241,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: """ @@ -259,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: """ diff --git a/twilio/rest/video/v1/recording.py b/twilio/rest/video/v1/recording.py index 20c836d2b0..f99a8322dd 100644 --- a/twilio/rest/video/v1/recording.py +++ b/twilio/rest/video/v1/recording.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -101,6 +102,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RecordingContext] = None @property @@ -136,6 +138,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RecordingInstance": """ Fetch the RecordingInstance @@ -154,6 +174,24 @@ async def fetch_async(self) -> "RecordingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -181,6 +219,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Recordings/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RecordingInstance @@ -188,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: @@ -200,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: @@ -212,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: """ @@ -231,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: """ @@ -261,6 +395,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: :param payload: Payload response from the API """ + return RecordingInstance(self._version, payload) def __repr__(self) -> str: @@ -375,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, @@ -406,6 +629,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -450,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( @@ -464,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, @@ -506,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( @@ -551,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 3895b9d4ba..ce2373eb9f 100644 --- a/twilio/rest/video/v1/recording_settings.py +++ b/twilio/rest/video/v1/recording_settings.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -120,6 +121,66 @@ async def create_async( encryption_enabled=encryption_enabled, ) + def create_with_http_info( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the RecordingSettingsInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + async def create_with_http_info_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the RecordingSettingsInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + def fetch(self) -> "RecordingSettingsInstance": """ Fetch the RecordingSettingsInstance @@ -138,6 +199,24 @@ async def fetch_async(self) -> "RecordingSettingsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingSettingsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RecordingSettingsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -160,6 +239,42 @@ def __init__(self, version: Version): self._uri = "/RecordingSettings/Default" + def _create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "AwsCredentialsSid": aws_credentials_sid, + "EncryptionKeySid": encryption_key_sid, + "AwsS3Url": aws_s3_url, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, friendly_name: str, @@ -181,6 +296,64 @@ def create( :returns: The created RecordingSettingsInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + return RecordingSettingsInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the RecordingSettingsInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + instance = RecordingSettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "FriendlyName": friendly_name, @@ -191,10 +364,15 @@ def create( "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), } ) + headers = values.of({}) - payload = self._version.create(method="POST", uri=self._uri, data=data) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RecordingSettingsInstance(self._version, payload) + headers["Accept"] = "application/json" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) async def create_async( self, @@ -217,22 +395,63 @@ async def create_async( :returns: The created RecordingSettingsInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "AwsCredentialsSid": aws_credentials_sid, - "EncryptionKeySid": encryption_key_sid, - "AwsS3Url": aws_s3_url, - "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), - "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, ) + return RecordingSettingsInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data + async def create_with_http_info_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to create the RecordingSettingsInstance and return response metadata + + :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: """ @@ -241,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: """ @@ -259,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: """ diff --git a/twilio/rest/video/v1/room/__init__.py b/twilio/rest/video/v1/room/__init__.py index c735e5516f..cdc626b3e3 100644 --- a/twilio/rest/video/v1/room/__init__.py +++ b/twilio/rest/video/v1/room/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,6 +24,7 @@ from twilio.rest.video.v1.room.participant import ParticipantList from twilio.rest.video.v1.room.recording_rules import RecordingRulesList from twilio.rest.video.v1.room.room_recording import RoomRecordingList +from twilio.rest.video.v1.room.transcriptions import TranscriptionsList class RoomInstance(InstanceResource): @@ -33,9 +35,9 @@ class RoomStatus(object): FAILED = "failed" class RoomType(object): + GROUP = "group" GO = "go" PEER_TO_PEER = "peer-to-peer" - GROUP = "group" GROUP_SMALL = "group-small" class VideoCodec(object): @@ -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-addresses#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 @@ -234,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: """ @@ -242,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: """ @@ -261,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" - 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: "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" + + 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: "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: """ @@ -353,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 @@ -371,6 +540,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoomInstance: :param payload: Payload response from the API """ + return RoomInstance(self._version, payload) def __repr__(self) -> str: @@ -395,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, @@ -404,35 +574,22 @@ def create( status_callback_method: Union[str, object] = values.unset, max_participants: Union[int, object] = values.unset, record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, media_region: Union[str, object] = values.unset, recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, audio_only: Union[bool, object] = values.unset, max_participant_duration: Union[int, object] = values.unset, empty_room_timeout: Union[int, object] = values.unset, unused_room_timeout: Union[int, object] = values.unset, large_room: Union[bool, object] = values.unset, - ) -> RoomInstance: + ) -> tuple: """ - Create the RoomInstance + Internal helper for create operation - :param enable_turn: Deprecated, now always considered to be true. - :param type: - :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource's `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. - :param status_callback: The URL 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-addresses#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( @@ -446,9 +603,15 @@ def create( "RecordParticipantsOnConnect": serialize.boolean_to_string( record_participants_on_connect ), + "TranscribeParticipantsOnConnect": serialize.boolean_to_string( + transcribe_participants_on_connect + ), "VideoCodecs": serialize.map(video_codecs, lambda e: e), "MediaRegion": media_region, "RecordingRules": serialize.object(recording_rules), + "TranscriptionsConfiguration": serialize.object( + transcriptions_configuration + ), "AudioOnly": serialize.boolean_to_string(audio_only), "MaxParticipantDuration": max_participant_duration, "EmptyRoomTimeout": empty_room_timeout, @@ -458,13 +621,15 @@ def create( ) headers = values.of({"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 RoomInstance(self._version, payload) - - async def create_async( + def create( self, enable_turn: Union[bool, object] = values.unset, type: Union["RoomInstance.RoomType", object] = values.unset, @@ -473,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, @@ -483,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-addresses#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). @@ -503,6 +672,118 @@ async def create_async( :returns: The created RoomInstance """ + payload, _, _ = self._create( + enable_turn=enable_turn, + type=type, + unique_name=unique_name, + status_callback=status_callback, + status_callback_method=status_callback_method, + max_participants=max_participants, + record_participants_on_connect=record_participants_on_connect, + transcribe_participants_on_connect=transcribe_participants_on_connect, + video_codecs=video_codecs, + media_region=media_region, + recording_rules=recording_rules, + transcriptions_configuration=transcriptions_configuration, + audio_only=audio_only, + max_participant_duration=max_participant_duration, + empty_room_timeout=empty_room_timeout, + unused_room_timeout=unused_room_timeout, + large_room=large_room, + ) + return RoomInstance(self._version, payload) + + def create_with_http_info( + self, + enable_turn: Union[bool, object] = values.unset, + type: Union["RoomInstance.RoomType", object] = values.unset, + unique_name: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + max_participants: Union[int, object] = values.unset, + record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, + video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, + media_region: Union[str, object] = values.unset, + recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, + audio_only: Union[bool, object] = values.unset, + max_participant_duration: Union[int, object] = values.unset, + empty_room_timeout: Union[int, object] = values.unset, + unused_room_timeout: Union[int, object] = values.unset, + large_room: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the RoomInstance and return response metadata + + :param enable_turn: Deprecated, now always considered to be true. + :param type: + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource's `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. + :param status_callback: The URL Twilio should call using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. + :param status_callback_method: The HTTP method Twilio should use to call `status_callback`. Can be `POST` or `GET`. + :param max_participants: The maximum number of concurrent Participants allowed in the room. The maximum allowed value is 50. + :param record_participants_on_connect: Whether to start recording when Participants connect. + :param transcribe_participants_on_connect: Whether to start transcriptions when Participants connect. If TranscriptionsConfiguration is not provided, default settings will be used. + :param video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. + :param media_region: The region for the Room's media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#group-rooms-media-servers). + :param recording_rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording + :param transcriptions_configuration: A collection of properties that describe transcription behaviour. If TranscribeParticipantsOnConnect is set to true and TranscriptionsConfiguration is not provided, default settings will be used. + :param audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. + :param max_participant_duration: The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). + :param empty_room_timeout: Configures how long (in minutes) a room will remain active after last participant leaves. Valid values range from 1 to 60 minutes (no fractions). + :param unused_room_timeout: Configures how long (in minutes) a room will remain active if no one joins. Valid values range from 1 to 60 minutes (no fractions). + :param large_room: When set to true, indicated that this is the large room. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + enable_turn=enable_turn, + type=type, + unique_name=unique_name, + status_callback=status_callback, + status_callback_method=status_callback_method, + max_participants=max_participants, + record_participants_on_connect=record_participants_on_connect, + transcribe_participants_on_connect=transcribe_participants_on_connect, + video_codecs=video_codecs, + media_region=media_region, + recording_rules=recording_rules, + transcriptions_configuration=transcriptions_configuration, + audio_only=audio_only, + max_participant_duration=max_participant_duration, + empty_room_timeout=empty_room_timeout, + unused_room_timeout=unused_room_timeout, + large_room=large_room, + ) + instance = RoomInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + enable_turn: Union[bool, object] = values.unset, + type: Union["RoomInstance.RoomType", object] = values.unset, + unique_name: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + max_participants: Union[int, object] = values.unset, + record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, + video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, + media_region: Union[str, object] = values.unset, + recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, + audio_only: Union[bool, object] = values.unset, + max_participant_duration: Union[int, object] = values.unset, + empty_room_timeout: Union[int, object] = values.unset, + unused_room_timeout: Union[int, object] = values.unset, + large_room: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -515,9 +796,15 @@ async def create_async( "RecordParticipantsOnConnect": serialize.boolean_to_string( record_participants_on_connect ), + "TranscribeParticipantsOnConnect": serialize.boolean_to_string( + transcribe_participants_on_connect + ), "VideoCodecs": serialize.map(video_codecs, lambda e: e), "MediaRegion": media_region, "RecordingRules": serialize.object(recording_rules), + "TranscriptionsConfiguration": serialize.object( + transcriptions_configuration + ), "AudioOnly": serialize.boolean_to_string(audio_only), "MaxParticipantDuration": max_participant_duration, "EmptyRoomTimeout": empty_room_timeout, @@ -527,12 +814,143 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -611,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, @@ -638,6 +1132,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -676,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( @@ -688,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, @@ -724,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( @@ -763,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 145d95429a..fdee154a0c 100644 --- a/twilio/rest/video/v1/room/participant/__init__.py +++ b/twilio/rest/video/v1/room/participant/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -31,6 +32,7 @@ class ParticipantInstance(InstanceResource): class Status(object): CONNECTED = "connected" DISCONNECTED = "disconnected" + RECONNECTING = "reconnecting" """ :ivar sid: The unique string that we created to identify the RoomParticipant resource. @@ -81,6 +83,7 @@ def __init__( "room_sid": room_sid, "sid": sid or self.sid, } + self._context: Optional[ParticipantContext] = None @property @@ -117,6 +120,24 @@ async def fetch_async(self) -> "ParticipantInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ParticipantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, status: Union["ParticipantInstance.Status", object] = values.unset ) -> "ParticipantInstance": @@ -145,6 +166,34 @@ async def update_async( status=status, ) + def update_with_http_info( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ApiResponse: + """ + Update the ParticipantInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + status=status, + ) + + async def update_with_http_info_async( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ParticipantInstance with HTTP info + + :param status: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + ) + @property def anonymize(self) -> AnonymizeList: """ @@ -207,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 @@ -214,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: """ @@ -234,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 - - :param status: + Internal helper for update operation - :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" + + 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["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, @@ -276,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({}) + + 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["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, @@ -305,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: """ @@ -375,6 +544,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: :param payload: Payload response from the API """ + return ParticipantInstance( self._version, payload, room_sid=self._solution["room_sid"] ) @@ -484,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, @@ -511,6 +757,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -549,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( @@ -561,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, @@ -597,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, @@ -636,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: """ @@ -651,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: """ @@ -663,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 e9a7f1383e..4a024d06a2 100644 --- a/twilio/rest/video/v1/room/participant/anonymize.py +++ b/twilio/rest/video/v1/room/participant/anonymize.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( "room_sid": room_sid, "sid": sid, } + self._context: Optional[AnonymizeContext] = None @property @@ -106,6 +108,24 @@ async def update_async(self) -> "AnonymizeInstance": """ return await self._proxy.update_async() + def update_with_http_info(self) -> ApiResponse: + """ + Update the AnonymizeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info() + + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the AnonymizeInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -137,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 @@ -144,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: """ @@ -166,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: """ diff --git a/twilio/rest/video/v1/room/participant/published_track.py b/twilio/rest/video/v1/room/participant/published_track.py index 1fa84827b6..ec1ebf09a4 100644 --- a/twilio/rest/video/v1/room/participant/published_track.py +++ b/twilio/rest/video/v1/room/participant/published_track.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -70,6 +71,7 @@ def __init__( "participant_sid": participant_sid, "sid": sid or self.sid, } + self._context: Optional[PublishedTrackContext] = None @property @@ -107,6 +109,24 @@ async def fetch_async(self) -> "PublishedTrackInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PublishedTrackInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PublishedTrackInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -140,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 @@ -147,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: """ @@ -168,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: """ @@ -200,6 +276,7 @@ def get_instance(self, payload: Dict[str, Any]) -> PublishedTrackInstance: :param payload: Payload response from the API """ + return PublishedTrackInstance( self._version, payload, @@ -290,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, @@ -309,6 +436,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -335,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( @@ -343,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, @@ -367,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, @@ -394,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: """ @@ -409,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: """ @@ -421,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 a155038493..f13f7e6473 100644 --- a/twilio/rest/video/v1/room/participant/subscribe_rules.py +++ b/twilio/rest/video/v1/room/participant/subscribe_rules.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -88,17 +89,29 @@ def __init__(self, version: Version, room_sid: str, participant_sid: str): ) ) - def fetch(self) -> SubscribeRulesInstance: + def _fetch(self) -> tuple: """ - Asynchronously fetch the SubscribeRulesInstance - + Internal helper for fetch operation - :returns: The fetched SubscribeRulesInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> SubscribeRulesInstance: + """ + Fetch the SubscribeRulesInstance + + :returns: The fetched SubscribeRulesInstance + """ + payload, _, _ = self._fetch() return SubscribeRulesInstance( self._version, payload, @@ -106,19 +119,45 @@ def fetch(self) -> SubscribeRulesInstance: participant_sid=self._solution["participant_sid"], ) - async def fetch_async(self) -> SubscribeRulesInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronously fetch the SubscribeRulesInstance + Fetch the SubscribeRulesInstance and return response metadata - :returns: The fetched SubscribeRulesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.fetch_async( + headers["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._fetch_async() return SubscribeRulesInstance( self._version, payload, @@ -126,15 +165,28 @@ async def fetch_async(self) -> SubscribeRulesInstance: participant_sid=self._solution["participant_sid"], ) - def update( - self, rules: Union[object, object] = values.unset - ) -> SubscribeRulesInstance: + async def fetch_with_http_info_async(self) -> ApiResponse: """ - Update the SubscribeRulesInstance + Asynchronously fetch the SubscribeRulesInstance and return response metadata - :param rules: A JSON-encoded array of subscribe rules. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. - :returns: The created SubscribeRulesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update(self, rules: Union[object, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -144,10 +196,25 @@ def update( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, 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, @@ -155,15 +222,31 @@ def update( participant_sid=self._solution["participant_sid"], ) - async def update_async( + def update_with_http_info( self, rules: Union[object, object] = values.unset - ) -> SubscribeRulesInstance: + ) -> ApiResponse: """ - Asynchronously update the SubscribeRulesInstance + Update the SubscribeRulesInstance and return response metadata :param rules: A JSON-encoded array of subscribe rules. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. - :returns: The created SubscribeRulesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update(rules=rules) + instance = SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self, rules: Union[object, object] = values.unset) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -173,10 +256,25 @@ async def update_async( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, 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, @@ -184,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 7c915095ec..de2ef19592 100644 --- a/twilio/rest/video/v1/room/participant/subscribed_track.py +++ b/twilio/rest/video/v1/room/participant/subscribed_track.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -72,6 +73,7 @@ def __init__( "participant_sid": participant_sid, "sid": sid or self.sid, } + self._context: Optional[SubscribedTrackContext] = None @property @@ -109,6 +111,24 @@ async def fetch_async(self) -> "SubscribedTrackInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscribedTrackInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscribedTrackInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -142,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 @@ -149,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: """ @@ -170,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: """ @@ -202,6 +278,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SubscribedTrackInstance: :param payload: Payload response from the API """ + return SubscribedTrackInstance( self._version, payload, @@ -292,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, @@ -311,6 +438,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -337,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( @@ -345,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, @@ -369,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, @@ -396,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: """ @@ -411,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: """ @@ -423,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 f85ebe896e..d399cd03d4 100644 --- a/twilio/rest/video/v1/room/recording_rules.py +++ b/twilio/rest/video/v1/room/recording_rules.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -73,47 +74,92 @@ def __init__(self, version: Version, room_sid: str): } self._uri = "/Rooms/{room_sid}/RecordingRules".format(**self._solution) - def fetch(self) -> RecordingRulesInstance: + def _fetch(self) -> tuple: """ - Asynchronously fetch the RecordingRulesInstance - + Internal helper for fetch operation - :returns: The fetched RecordingRulesInstance + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + headers["Accept"] = "application/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingRulesInstance: + """ + Fetch the RecordingRulesInstance + + :returns: The fetched RecordingRulesInstance + """ + payload, _, _ = self._fetch() return RecordingRulesInstance( self._version, payload, room_sid=self._solution["room_sid"] ) - async def fetch_async(self) -> RecordingRulesInstance: + def fetch_with_http_info(self) -> ApiResponse: """ - Asynchronously fetch the RecordingRulesInstance + Fetch the RecordingRulesInstance and return response metadata - :returns: The fetched RecordingRulesInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.fetch_async( + headers["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._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( @@ -123,23 +169,51 @@ def update( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, 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( @@ -149,14 +223,45 @@ async def update_async( ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, 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 db67f29947..697904b713 100644 --- a/twilio/rest/video/v1/room/room_recording.py +++ b/twilio/rest/video/v1/room/room_recording.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -102,6 +103,7 @@ def __init__( "room_sid": room_sid, "sid": sid or self.sid, } + self._context: Optional[RoomRecordingContext] = None @property @@ -138,6 +140,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RoomRecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoomRecordingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RoomRecordingInstance": """ Fetch the RoomRecordingInstance @@ -156,6 +176,24 @@ async def fetch_async(self) -> "RoomRecordingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoomRecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RoomRecordingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -185,6 +223,20 @@ def __init__(self, version: Version, room_sid: str, sid: str): } self._uri = "/Rooms/{room_sid}/Recordings/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RoomRecordingInstance @@ -192,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: @@ -204,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: @@ -216,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: """ @@ -236,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: """ @@ -267,6 +403,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RoomRecordingInstance: :param payload: Payload response from the API """ + return RoomRecordingInstance( self._version, payload, room_sid=self._solution["room_sid"] ) @@ -376,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, @@ -403,6 +616,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -441,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( @@ -453,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, @@ -489,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, @@ -528,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: """ @@ -543,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: """ @@ -555,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 4394ab1a2d..3bcc12e228 100644 --- a/twilio/rest/voice/VoiceBase.py +++ b/twilio/rest/voice/VoiceBase.py @@ -14,6 +14,7 @@ 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): @@ -26,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: @@ -36,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/archived_call.py b/twilio/rest/voice/v1/archived_call.py index ec8a5bb68e..090f21d452 100644 --- a/twilio/rest/voice/v1/archived_call.py +++ b/twilio/rest/voice/v1/archived_call.py @@ -13,6 +13,8 @@ """ 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 @@ -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: """ diff --git a/twilio/rest/voice/v1/byoc_trunk.py b/twilio/rest/voice/v1/byoc_trunk.py index 1c3e301d7a..f6e053c0dc 100644 --- a/twilio/rest/voice/v1/byoc_trunk.py +++ b/twilio/rest/voice/v1/byoc_trunk.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -71,6 +72,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ByocTrunkContext] = None @property @@ -106,6 +108,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ByocTrunkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ByocTrunkInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ByocTrunkInstance": """ Fetch the ByocTrunkInstance @@ -124,6 +144,24 @@ async def fetch_async(self) -> "ByocTrunkInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ByocTrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ByocTrunkInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -208,6 +246,90 @@ async def update_async( from_domain_sid=from_domain_sid, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the ByocTrunkInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ByocTrunkInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -235,6 +357,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/ByocTrunks/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ByocTrunkInstance @@ -242,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: @@ -254,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: @@ -266,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: """ @@ -285,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, @@ -309,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, @@ -340,16 +549,17 @@ def update( "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, @@ -363,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. @@ -378,72 +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": serialize.boolean_to_string(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, @@ -455,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`. @@ -470,10 +629,44 @@ 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( + 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, @@ -487,15 +680,191 @@ def create( "FromDomainSid": from_domain_sid, } ) - headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers = values.of({}) - payload = self._version.create( + 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"]) + + 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, @@ -509,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. @@ -524,6 +893,83 @@ async def create_async( :returns: The created ByocTrunkInstance """ + payload, _, _ = self._create( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + return ByocTrunkInstance(self._version, payload) + + def create_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the ByocTrunkInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + instance = ByocTrunkInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -541,12 +987,101 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -597,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, @@ -616,6 +1201,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -642,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( @@ -650,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, @@ -674,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( @@ -701,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 4e65be6519..2d8d1ac47e 100644 --- a/twilio/rest/voice/v1/connection_policy/__init__.py +++ b/twilio/rest/voice/v1/connection_policy/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -56,6 +57,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ConnectionPolicyContext] = None @property @@ -91,6 +93,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectionPolicyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectionPolicyInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ConnectionPolicyInstance": """ Fetch the ConnectionPolicyInstance @@ -109,6 +129,24 @@ async def fetch_async(self) -> "ConnectionPolicyInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectionPolicyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectionPolicyInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset ) -> "ConnectionPolicyInstance": @@ -137,6 +175,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the ConnectionPolicyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectionPolicyInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + @property def targets(self) -> ConnectionPolicyTargetList: """ @@ -173,6 +239,20 @@ def __init__(self, version: Version, sid: str): self._targets: Optional[ConnectionPolicyTargetList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ConnectionPolicyInstance @@ -180,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: @@ -192,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: @@ -204,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: """ @@ -223,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 @@ -245,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( @@ -271,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: @@ -317,6 +539,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConnectionPolicyInstance: :param payload: Payload response from the API """ + return ConnectionPolicyInstance(self._version, payload) def __repr__(self) -> str: @@ -341,15 +564,12 @@ def __init__(self, version: Version): self._uri = "/ConnectionPolicies" - def create( - self, friendly_name: Union[str, object] = values.unset - ) -> ConnectionPolicyInstance: + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: """ - Create the ConnectionPolicyInstance - - :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. + Internal helper for create operation - :returns: The created ConnectionPolicyInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -359,22 +579,50 @@ def create( ) headers = values.of({"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 ConnectionPolicyInstance(self._version, payload) - - async def create_async( + def create( self, friendly_name: Union[str, object] = values.unset ) -> ConnectionPolicyInstance: """ - Asynchronously create the ConnectionPolicyInstance + Create the ConnectionPolicyInstance :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. :returns: The created ConnectionPolicyInstance """ + payload, _, _ = self._create(friendly_name=friendly_name) + return ConnectionPolicyInstance(self._version, payload) + + def create_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the ConnectionPolicyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(friendly_name=friendly_name) + instance = ConnectionPolicyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -383,12 +631,43 @@ async def create_async( ) headers = values.of({"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, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Asynchronously create the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The created ConnectionPolicyInstance + """ + payload, _, _ = await self._create_async(friendly_name=friendly_name) return ConnectionPolicyInstance(self._version, payload) + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the ConnectionPolicyInstance and return response metadata + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + friendly_name=friendly_name + ) + instance = ConnectionPolicyInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -439,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, @@ -458,6 +787,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -484,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( @@ -492,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, @@ -516,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( @@ -543,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 05daee6c79..2f84ce2e4d 100644 --- a/twilio/rest/voice/v1/connection_policy/connection_policy_target.py +++ b/twilio/rest/voice/v1/connection_policy/connection_policy_target.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -66,6 +67,7 @@ def __init__( "connection_policy_sid": connection_policy_sid, "sid": sid or self.sid, } + self._context: Optional[ConnectionPolicyTargetContext] = None @property @@ -102,6 +104,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ConnectionPolicyTargetInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "ConnectionPolicyTargetInstance": """ Fetch the ConnectionPolicyTargetInstance @@ -120,6 +140,24 @@ async def fetch_async(self) -> "ConnectionPolicyTargetInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectionPolicyTargetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset, @@ -174,6 +212,60 @@ async def update_async( enabled=enabled, ) + def update_with_http_info( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the ConnectionPolicyTargetInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + + async def update_with_http_info_async( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ConnectionPolicyTargetInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -205,6 +297,20 @@ def __init__(self, version: Version, connection_policy_sid: str, sid: str): **self._solution ) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the ConnectionPolicyTargetInstance @@ -212,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: @@ -224,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: @@ -236,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: """ @@ -256,38 +435,45 @@ 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, @@ -297,13 +483,42 @@ def update( "Enabled": serialize.boolean_to_string(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, + 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, @@ -311,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. @@ -328,8 +543,38 @@ 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, @@ -339,13 +584,42 @@ async def update_async( "Enabled": serialize.boolean_to_string(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, + 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, @@ -353,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 @@ -371,6 +679,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ConnectionPolicyTargetInstanc :param payload: Payload response from the API """ + return ConnectionPolicyTargetInstance( self._version, payload, @@ -406,24 +715,19 @@ def __init__(self, version: Version, connection_policy_sid: str): **self._solution ) - def create( + def _create( self, target: str, friendly_name: Union[str, object] = values.unset, priority: Union[int, object] = values.unset, weight: Union[int, object] = values.unset, enabled: Union[bool, object] = values.unset, - ) -> ConnectionPolicyTargetInstance: + ) -> tuple: """ - Create the ConnectionPolicyTargetInstance - - :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. - :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. - :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. - :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. - :param enabled: Whether the Target is enabled. The default is `true`. + Internal helper for create operation - :returns: The created ConnectionPolicyTargetInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -437,26 +741,56 @@ def create( ) headers = values.of({"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, + 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. @@ -464,7 +798,35 @@ async def create_async( :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. :param enabled: Whether the Target is enabled. The default is `true`. - :returns: The created ConnectionPolicyTargetInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + target=target, + friendly_name=friendly_name, + priority=priority, + weight=weight, + enabled=enabled, + ) + instance = ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + target: str, + friendly_name: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -478,16 +840,79 @@ async def create_async( ) headers = values.of({"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, + 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, @@ -538,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, @@ -557,6 +1032,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -583,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( @@ -591,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, @@ -615,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, @@ -642,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: """ @@ -657,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: """ @@ -669,7 +1286,9 @@ async def get_page_async(self, target_url: str) -> ConnectionPolicyTargetPage: :returns: Page of ConnectionPolicyTargetInstance """ response = await self._version.domain.twilio.request_async("GET", target_url) - return ConnectionPolicyTargetPage(self._version, response, self._solution) + return ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) def get(self, sid: str) -> ConnectionPolicyTargetContext: """ diff --git a/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py b/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py index 5b0d35d3d2..fc4a80d633 100644 --- a/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py +++ b/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,13 +58,12 @@ def __init__(self, version: Version): self._uri = "/DialingPermissions/BulkCountryUpdates" - def create(self, update_request: str) -> BulkCountryUpdateInstance: + def _create(self, update_request: str) -> tuple: """ - Create the BulkCountryUpdateInstance + Internal helper for create operation - :param update_request: URL encoded JSON array of update objects. example : `[ { \\\"iso_code\\\": \\\"GB\\\", \\\"low_risk_numbers_enabled\\\": \\\"true\\\", \\\"high_risk_special_numbers_enabled\\\":\\\"true\\\", \\\"high_risk_tollfraud_numbers_enabled\\\": \\\"false\\\" } ]` - - :returns: The created BulkCountryUpdateInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -73,19 +73,43 @@ def create(self, update_request: str) -> BulkCountryUpdateInstance: ) headers = values.of({"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, 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( @@ -95,12 +119,39 @@ async def create_async(self, update_request: str) -> BulkCountryUpdateInstance: ) headers = values.of({"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, 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 2b9285c112..ed666a1eb8 100644 --- a/twilio/rest/voice/v1/dialing_permissions/country/__init__.py +++ b/twilio/rest/voice/v1/dialing_permissions/country/__init__.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -61,6 +62,7 @@ def __init__( self._solution = { "iso_code": iso_code or self.iso_code, } + self._context: Optional[CountryContext] = None @property @@ -96,6 +98,24 @@ async def fetch_async(self) -> "CountryInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CountryInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + @property def highrisk_special_prefixes(self) -> HighriskSpecialPrefixList: """ @@ -132,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 @@ -139,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: """ @@ -158,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: @@ -200,6 +272,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -314,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, @@ -345,6 +506,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( iso_code=iso_code, @@ -389,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( @@ -403,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, @@ -451,7 +700,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( @@ -502,11 +757,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 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 9303f2c9ae..9e63e78d24 100644 --- a/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py +++ b/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -53,6 +54,7 @@ def get_instance(self, payload: Dict[str, Any]) -> HighriskSpecialPrefixInstance :param payload: Payload response from the API """ + return HighriskSpecialPrefixInstance( self._version, payload, iso_code=self._solution["iso_code"] ) @@ -138,6 +140,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams HighriskSpecialPrefixInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams HighriskSpecialPrefixInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -157,6 +209,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -183,6 +236,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -191,6 +245,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists HighriskSpecialPrefixInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists HighriskSpecialPrefixInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -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, self._solution) + return HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) + + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with HighriskSpecialPrefixPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with HighriskSpecialPrefixPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> HighriskSpecialPrefixPage: """ @@ -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 20d845673a..e1787b3ce5 100644 --- a/twilio/rest/voice/v1/dialing_permissions/settings.py +++ b/twilio/rest/voice/v1/dialing_permissions/settings.py @@ -14,6 +14,7 @@ from typing import Any, Dict, Optional, Union from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,24 @@ async def fetch_async(self) -> "SettingsInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SettingsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SettingsInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, dialing_permissions_inheritance: Union[bool, object] = values.unset ) -> "SettingsInstance": @@ -96,6 +115,34 @@ async def update_async( dialing_permissions_inheritance=dialing_permissions_inheritance, ) + def update_with_http_info( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Update the SettingsInstance with HTTP info + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + dialing_permissions_inheritance=dialing_permissions_inheritance, + ) + + async def update_with_http_info_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SettingsInstance with HTTP info + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + dialing_permissions_inheritance=dialing_permissions_inheritance, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -118,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 @@ -125,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: """ @@ -143,27 +231,36 @@ 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( + def _update( self, dialing_permissions_inheritance: Union[bool, object] = values.unset - ) -> SettingsInstance: + ) -> tuple: """ - Update the SettingsInstance + Internal helper for update operation - :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. - - :returns: The updated SettingsInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "DialingPermissionsInheritance": serialize.boolean_to_string( @@ -171,25 +268,57 @@ def update( ), } ) + 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" - async def update_async( + 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 ) -> SettingsInstance: """ - Asynchronous coroutine to update the SettingsInstance + Update the SettingsInstance :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. :returns: The updated SettingsInstance """ + payload, _, _ = self._update( + dialing_permissions_inheritance=dialing_permissions_inheritance + ) + return SettingsInstance(self._version, payload) + + def update_with_http_info( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Update the SettingsInstance and return response metadata + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + dialing_permissions_inheritance=dialing_permissions_inheritance + ) + instance = SettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = values.of( { "DialingPermissionsInheritance": serialize.boolean_to_string( @@ -197,15 +326,47 @@ 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, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> SettingsInstance: + """ + Asynchronous coroutine to update the SettingsInstance + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: The updated SettingsInstance + """ + payload, _, _ = await self._update_async( + dialing_permissions_inheritance=dialing_permissions_inheritance + ) return SettingsInstance(self._version, payload) + async def update_with_http_info_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SettingsInstance and return response metadata + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + dialing_permissions_inheritance=dialing_permissions_inheritance + ) + instance = SettingsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/voice/v1/ip_record.py b/twilio/rest/voice/v1/ip_record.py index 5c103bf98e..9a17301f6d 100644 --- a/twilio/rest/voice/v1/ip_record.py +++ b/twilio/rest/voice/v1/ip_record.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -57,6 +58,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[IpRecordContext] = None @property @@ -92,6 +94,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the IpRecordInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpRecordInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "IpRecordInstance": """ Fetch the IpRecordInstance @@ -110,6 +130,24 @@ async def fetch_async(self) -> "IpRecordInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpRecordInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpRecordInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, friendly_name: Union[str, object] = values.unset ) -> "IpRecordInstance": @@ -138,6 +176,34 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Update the IpRecordInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IpRecordInstance with HTTP info + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -165,6 +231,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/IpRecords/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the IpRecordInstance @@ -172,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: @@ -184,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: @@ -196,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: """ @@ -215,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 @@ -237,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 @@ -261,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: """ @@ -293,6 +511,7 @@ def get_instance(self, payload: Dict[str, Any]) -> IpRecordInstance: :param payload: Payload response from the API """ + return IpRecordInstance(self._version, payload) def __repr__(self) -> str: @@ -317,20 +536,17 @@ def __init__(self, version: Version): self._uri = "/IpRecords" - def create( + def _create( self, ip_address: str, friendly_name: Union[str, object] = values.unset, cidr_prefix_length: Union[int, object] = values.unset, - ) -> IpRecordInstance: + ) -> tuple: """ - Create the IpRecordInstance - - :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. + Internal helper for create operation - :returns: The created IpRecordInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -342,20 +558,22 @@ def create( ) headers = values.of({"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 IpRecordInstance(self._version, payload) - - async def create_async( + def create( self, ip_address: str, friendly_name: Union[str, object] = values.unset, cidr_prefix_length: Union[int, object] = values.unset, ) -> IpRecordInstance: """ - Asynchronously create the IpRecordInstance + Create the IpRecordInstance :param ip_address: An IP address in dotted decimal notation, IPv4 only. :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. @@ -363,6 +581,48 @@ async def create_async( :returns: The created IpRecordInstance """ + payload, _, _ = self._create( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + return IpRecordInstance(self._version, payload) + + def create_with_http_info( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Create the IpRecordInstance and return response metadata + + :param ip_address: An IP address in dotted decimal notation, IPv4 only. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + instance = IpRecordInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -373,12 +633,59 @@ async def create_async( ) headers = values.of({"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, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpRecordInstance: + """ + Asynchronously create the IpRecordInstance + + :param ip_address: An IP address in dotted decimal notation, IPv4 only. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + + :returns: The created IpRecordInstance + """ + payload, _, _ = await self._create_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) return IpRecordInstance(self._version, payload) + async def create_with_http_info_async( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the IpRecordInstance and return response metadata + + :param ip_address: An IP address in dotted decimal notation, IPv4 only. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + instance = IpRecordInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -429,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, @@ -448,6 +805,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -474,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( @@ -482,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, @@ -506,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( @@ -533,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 50e2bbe361..d4c30d09f5 100644 --- a/twilio/rest/voice/v1/source_ip_mapping.py +++ b/twilio/rest/voice/v1/source_ip_mapping.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -51,6 +52,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SourceIpMappingContext] = None @property @@ -86,6 +88,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SourceIpMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SourceIpMappingInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SourceIpMappingInstance": """ Fetch the SourceIpMappingInstance @@ -104,6 +124,24 @@ async def fetch_async(self) -> "SourceIpMappingInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SourceIpMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SourceIpMappingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update(self, sip_domain_sid: str) -> "SourceIpMappingInstance": """ Update the SourceIpMappingInstance @@ -128,6 +166,30 @@ async def update_async(self, sip_domain_sid: str) -> "SourceIpMappingInstance": sip_domain_sid=sip_domain_sid, ) + def update_with_http_info(self, sip_domain_sid: str) -> ApiResponse: + """ + Update the SourceIpMappingInstance with HTTP info + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + sip_domain_sid=sip_domain_sid, + ) + + async def update_with_http_info_async(self, sip_domain_sid: str) -> ApiResponse: + """ + Asynchronous coroutine to update the SourceIpMappingInstance with HTTP info + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + sip_domain_sid=sip_domain_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -155,6 +217,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/SourceIpMappings/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SourceIpMappingInstance @@ -162,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: @@ -174,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: @@ -186,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: """ @@ -205,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({}) - 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, 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 @@ -283,6 +495,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SourceIpMappingInstance: :param payload: Payload response from the API """ + return SourceIpMappingInstance(self._version, payload) def __repr__(self) -> str: @@ -307,16 +520,12 @@ def __init__(self, version: Version): self._uri = "/SourceIpMappings" - def create( - self, ip_record_sid: str, sip_domain_sid: str - ) -> SourceIpMappingInstance: + def _create(self, ip_record_sid: str, sip_domain_sid: str) -> tuple: """ - Create the SourceIpMappingInstance + Internal helper for create operation - :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. - :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. - - :returns: The created SourceIpMappingInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -327,23 +536,54 @@ def create( ) headers = values.of({"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 SourceIpMappingInstance(self._version, payload) - - async def create_async( + def create( self, ip_record_sid: str, sip_domain_sid: str ) -> SourceIpMappingInstance: """ - Asynchronously create the SourceIpMappingInstance + Create the SourceIpMappingInstance :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. :returns: The created SourceIpMappingInstance """ + payload, _, _ = self._create( + ip_record_sid=ip_record_sid, sip_domain_sid=sip_domain_sid + ) + return SourceIpMappingInstance(self._version, payload) + + def create_with_http_info( + self, ip_record_sid: str, sip_domain_sid: str + ) -> ApiResponse: + """ + Create the SourceIpMappingInstance and return response metadata + + :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + ip_record_sid=ip_record_sid, sip_domain_sid=sip_domain_sid + ) + instance = SourceIpMappingInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, ip_record_sid: str, sip_domain_sid: str) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -353,12 +593,47 @@ async def create_async( ) headers = values.of({"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, ip_record_sid: str, sip_domain_sid: str + ) -> SourceIpMappingInstance: + """ + Asynchronously create the SourceIpMappingInstance + + :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The created SourceIpMappingInstance + """ + payload, _, _ = await self._create_async( + ip_record_sid=ip_record_sid, sip_domain_sid=sip_domain_sid + ) return SourceIpMappingInstance(self._version, payload) + async def create_with_http_info_async( + self, ip_record_sid: str, sip_domain_sid: str + ) -> ApiResponse: + """ + Asynchronously create the SourceIpMappingInstance and return response metadata + + :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + ip_record_sid=ip_record_sid, sip_domain_sid=sip_domain_sid + ) + instance = SourceIpMappingInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, limit: Optional[int] = None, @@ -409,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, @@ -428,6 +753,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -454,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( @@ -462,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, @@ -486,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( @@ -513,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/v1/command.py b/twilio/rest/wireless/v1/command.py index 3dc78e9b8f..caad0d64b8 100644 --- a/twilio/rest/wireless/v1/command.py +++ b/twilio/rest/wireless/v1/command.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -87,6 +88,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CommandContext] = None @property @@ -122,6 +124,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the CommandInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CommandInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "CommandInstance": """ Fetch the CommandInstance @@ -140,6 +160,24 @@ async def fetch_async(self) -> "CommandInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the CommandInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def __repr__(self) -> str: """ Provide a friendly representation @@ -167,6 +205,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Commands/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the CommandInstance @@ -174,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: @@ -186,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: @@ -198,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: """ @@ -217,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: """ @@ -247,6 +381,7 @@ def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: :param payload: Payload response from the API """ + return CommandInstance(self._version, payload) def __repr__(self) -> str: @@ -271,7 +406,7 @@ def __init__(self, version: Version): self._uri = "/Commands" - def create( + def _create( self, command: str, sim: Union[str, object] = values.unset, @@ -280,19 +415,12 @@ def create( command_mode: Union["CommandInstance.CommandMode", object] = values.unset, include_sid: Union[str, object] = values.unset, delivery_receipt_requested: Union[bool, object] = values.unset, - ) -> CommandInstance: + ) -> tuple: """ - Create the CommandInstance - - :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. - :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. - :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. - :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. - :param command_mode: - :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. - :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + Internal helper for create operation - :returns: The created CommandInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -310,13 +438,15 @@ def create( ) headers = values.of({"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 CommandInstance(self._version, payload) - - async def create_async( + def create( self, command: str, sim: Union[str, object] = values.unset, @@ -327,7 +457,7 @@ async def create_async( delivery_receipt_requested: Union[bool, object] = values.unset, ) -> CommandInstance: """ - Asynchronously create the CommandInstance + Create the CommandInstance :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. @@ -339,6 +469,68 @@ async def create_async( :returns: The created CommandInstance """ + payload, _, _ = self._create( + command=command, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + delivery_receipt_requested=delivery_receipt_requested, + ) + return CommandInstance(self._version, payload) + + def create_with_http_info( + self, + command: str, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union["CommandInstance.CommandMode", object] = values.unset, + include_sid: Union[str, object] = values.unset, + delivery_receipt_requested: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Create the CommandInstance and return response metadata + + :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. + :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. + :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. + :param command_mode: + :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. + :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + command=command, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + delivery_receipt_requested=delivery_receipt_requested, + ) + instance = CommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + command: str, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union["CommandInstance.CommandMode", object] = values.unset, + include_sid: Union[str, object] = values.unset, + delivery_receipt_requested: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -355,12 +547,83 @@ async def create_async( ) headers = values.of({"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, + command: str, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union["CommandInstance.CommandMode", object] = values.unset, + include_sid: Union[str, object] = values.unset, + delivery_receipt_requested: Union[bool, object] = values.unset, + ) -> CommandInstance: + """ + Asynchronously create the CommandInstance + + :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. + :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. + :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. + :param command_mode: + :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. + :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + + :returns: The created CommandInstance + """ + payload, _, _ = await self._create_async( + command=command, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + delivery_receipt_requested=delivery_receipt_requested, + ) return CommandInstance(self._version, payload) + async def create_with_http_info_async( + self, + command: str, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union["CommandInstance.CommandMode", object] = values.unset, + include_sid: Union[str, object] = values.unset, + delivery_receipt_requested: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CommandInstance and return response metadata + + :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. + :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. + :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. + :param command_mode: + :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. + :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + command=command, + sim=sim, + callback_method=callback_method, + callback_url=callback_url, + command_mode=command_mode, + include_sid=include_sid, + delivery_receipt_requested=delivery_receipt_requested, + ) + instance = CommandInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, sim: Union[str, object] = values.unset, @@ -439,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, @@ -466,6 +805,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -504,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( @@ -516,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, @@ -552,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( @@ -591,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 5370ef2ae3..77742cf2ba 100644 --- a/twilio/rest/wireless/v1/rate_plan.py +++ b/twilio/rest/wireless/v1/rate_plan.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,6 +24,11 @@ class RatePlanInstance(InstanceResource): + + class DataLimitStrategy(object): + BLOCK = "block" + THROTTLE = "throttle" + """ :ivar sid: The unique string that we created to identify the RatePlan resource. :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. @@ -79,6 +85,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RatePlanContext] = None @property @@ -114,6 +121,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the RatePlanInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RatePlanInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "RatePlanInstance": """ Fetch the RatePlanInstance @@ -132,6 +157,24 @@ async def fetch_async(self) -> "RatePlanInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RatePlanInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the RatePlanInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -168,6 +211,42 @@ async def update_async( friendly_name=friendly_name, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the RatePlanInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + friendly_name=friendly_name, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the RatePlanInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -195,6 +274,20 @@ def __init__(self, version: Version, sid: str): } self._uri = "/RatePlans/{sid}".format(**self._solution) + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the RatePlanInstance @@ -202,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: @@ -214,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: @@ -226,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: """ @@ -245,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, @@ -270,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, @@ -298,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: """ @@ -331,6 +580,7 @@ def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: :param payload: Payload response from the API """ + return RatePlanInstance(self._version, payload) def __repr__(self) -> str: @@ -355,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, @@ -368,23 +618,15 @@ def create( international_roaming: Union[List[str], object] = values.unset, national_roaming_data_limit: Union[int, object] = values.unset, international_roaming_data_limit: Union[int, object] = values.unset, - ) -> RatePlanInstance: + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> tuple: """ - Create the RatePlanInstance - - :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. + Internal helper for create operation - :returns: The created RatePlanInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -404,17 +646,20 @@ def create( ), "NationalRoamingDataLimit": national_roaming_data_limit, "InternationalRoamingDataLimit": international_roaming_data_limit, + "DataLimitStrategy": data_limit_strategy, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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 RatePlanInstance(self._version, payload) - - async def create_async( + def create( self, unique_name: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -427,9 +672,12 @@ async def create_async( international_roaming: Union[List[str], object] = values.unset, national_roaming_data_limit: Union[int, object] = values.unset, international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, ) -> RatePlanInstance: """ - Asynchronously create the RatePlanInstance + Create the RatePlanInstance :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. @@ -442,9 +690,101 @@ async def create_async( :param international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. :param national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming) for more info. :param international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :param data_limit_strategy: :returns: The created RatePlanInstance """ + payload, _, _ = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + national_roaming_data_limit=national_roaming_data_limit, + international_roaming_data_limit=international_roaming_data_limit, + data_limit_strategy=data_limit_strategy, + ) + return RatePlanInstance(self._version, payload) + + def create_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + national_roaming_data_limit: Union[int, object] = values.unset, + international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> ApiResponse: + """ + Create the RatePlanInstance and return response metadata + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + :param data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. + :param data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB and the default value is `1000`. + :param data_metering: The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + :param messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_enabled: Deprecated. + :param national_roaming_enabled: Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). + :param international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. + :param national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming) for more info. + :param international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :param data_limit_strategy: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + unique_name=unique_name, + friendly_name=friendly_name, + data_enabled=data_enabled, + data_limit=data_limit, + data_metering=data_metering, + messaging_enabled=messaging_enabled, + voice_enabled=voice_enabled, + national_roaming_enabled=national_roaming_enabled, + international_roaming=international_roaming, + national_roaming_data_limit=national_roaming_data_limit, + international_roaming_data_limit=international_roaming_data_limit, + data_limit_strategy=data_limit_strategy, + ) + instance = RatePlanInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + national_roaming_data_limit: Union[int, object] = values.unset, + international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -463,16 +803,122 @@ async def create_async( ), "NationalRoamingDataLimit": national_roaming_data_limit, "InternationalRoamingDataLimit": international_roaming_data_limit, + "DataLimitStrategy": data_limit_strategy, } ) headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - 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, + 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, @@ -523,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, @@ -542,6 +1038,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -568,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( @@ -576,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, @@ -600,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( @@ -627,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 f0d21c447e..33fee1d428 100644 --- a/twilio/rest/wireless/v1/sim/__init__.py +++ b/twilio/rest/wireless/v1/sim/__init__.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -107,6 +108,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SimContext] = None @property @@ -142,6 +144,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SimInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SimInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "SimInstance": """ Fetch the SimInstance @@ -160,6 +180,24 @@ async def fetch_async(self) -> "SimInstance": """ return await self._proxy.fetch_async() + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SimInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + def update( self, unique_name: Union[str, object] = values.unset, @@ -292,6 +330,138 @@ async def update_async( account_sid=account_sid, ) + def update_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the SimInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + reset_status=reset_status, + account_sid=account_sid, + ) + + async def update_with_http_info_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the SimInstance with HTTP info + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + reset_status=reset_status, + account_sid=account_sid, + ) + @property def data_sessions(self) -> DataSessionList: """ @@ -336,6 +506,20 @@ def __init__(self, version: Version, sid: str): self._data_sessions: Optional[DataSessionList] = None self._usage_records: Optional[UsageRecordList] = None + def _delete(self) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self) -> bool: """ Deletes the SimInstance @@ -343,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: @@ -355,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: @@ -367,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: """ @@ -386,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, @@ -418,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/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. - :param status: - :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. - :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. - :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. - :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. - :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. - :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). - :param voice_fallback_method: Deprecated. - :param voice_fallback_url: Deprecated. - :param voice_method: Deprecated. - :param voice_url: Deprecated. - :param reset_status: - :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + Internal helper for update operation - :returns: The updated SimInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "UniqueName": unique_name, @@ -465,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, @@ -496,7 +746,7 @@ async def update_async( account_sid: Union[str, object] = values.unset, ) -> SimInstance: """ - Asynchronous coroutine to update the SimInstance + Update the SimInstance :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. @@ -519,37 +769,291 @@ 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, - "ResetStatus": reset_status, - "AccountSid": account_sid, - } - ) - - 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, + 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: """ @@ -592,6 +1096,7 @@ def get_instance(self, payload: Dict[str, Any]) -> SimInstance: :param payload: Payload response from the API """ + return SimInstance(self._version, payload) def __repr__(self) -> str: @@ -700,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, @@ -729,6 +1316,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -770,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( @@ -783,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, @@ -822,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( @@ -864,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 649eb49631..cb0c14dc69 100644 --- a/twilio/rest/wireless/v1/sim/data_session.py +++ b/twilio/rest/wireless/v1/sim/data_session.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import deserialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -94,6 +95,7 @@ def get_instance(self, payload: Dict[str, Any]) -> DataSessionInstance: :param payload: Payload response from the API """ + return DataSessionInstance( self._version, payload, sim_sid=self._solution["sim_sid"] ) @@ -175,6 +177,56 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams DataSessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info(page_size=limits["page_size"]) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams DataSessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, limit: Optional[int] = None, @@ -194,6 +246,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -220,6 +273,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -228,6 +282,56 @@ async def list_async( ) ] + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists DataSessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists DataSessionInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, page_token: Union[str, object] = values.unset, @@ -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 8b1db6d0da..5b1c6b2512 100644 --- a/twilio/rest/wireless/v1/sim/usage_record.py +++ b/twilio/rest/wireless/v1/sim/usage_record.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -68,6 +69,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: :param payload: Payload response from the API """ + return UsageRecordInstance( self._version, payload, sim_sid=self._solution["sim_sid"] ) @@ -165,6 +167,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, end: Union[datetime, object] = values.unset, @@ -190,6 +256,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end=end, @@ -225,6 +292,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -236,6 +304,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, end: Union[datetime, object] = values.unset, @@ -269,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, @@ -305,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: """ @@ -320,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: """ @@ -332,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 43e34469ce..034ab18ab2 100644 --- a/twilio/rest/wireless/v1/usage_record.py +++ b/twilio/rest/wireless/v1/usage_record.py @@ -15,6 +15,7 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator from twilio.base import serialize, values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -62,6 +63,7 @@ def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: :param payload: Payload response from the API """ + return UsageRecordInstance(self._version, payload) def __repr__(self) -> str: @@ -152,6 +154,70 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_with_http_info( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, end: Union[datetime, object] = values.unset, @@ -177,6 +243,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end=end, @@ -212,6 +279,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -223,6 +291,74 @@ async def list_async( ) ] + def list_with_http_info( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists UsageRecordInstance and returns headers from first page + + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + def page( self, end: Union[datetime, object] = values.unset, @@ -256,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( @@ -292,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/voice_response.py b/twilio/twiml/voice_response.py index c6d453e143..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 ) ) @@ -678,6 +687,7 @@ def transcription( speech_model=None, hints=None, enable_automatic_punctuation=None, + intelligence_service=None, **kwargs ): """ @@ -696,6 +706,7 @@ def transcription( :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 @@ -715,6 +726,7 @@ def transcription( speech_model=speech_model, hints=hints, enable_automatic_punctuation=enable_automatic_punctuation, + intelligence_service=intelligence_service, **kwargs ) ) @@ -897,6 +909,7 @@ def transcription( speech_model=None, hints=None, enable_automatic_punctuation=None, + intelligence_service=None, **kwargs ): """ @@ -915,6 +928,7 @@ def transcription( :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 @@ -934,10 +948,57 @@ def transcription( 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""" @@ -2169,6 +2230,7 @@ def conference( wait_method=None, max_participants=None, record=None, + recording_configuration_id=None, region=None, coach=None, trim=None, @@ -2195,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 @@ -2222,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, @@ -2345,7 +2409,7 @@ def sim(self, sim_sid, **kwargs): def sip( self, - sip_url, + sip_url=None, username=None, password=None, url=None, @@ -2386,7 +2450,7 @@ def sip( """ return self.nest( Sip( - sip_url, + sip_url=sip_url, username=username, password=password, url=url, @@ -2446,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""" @@ -2492,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): @@ -2725,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"""