diff --git a/examples/go/go-client/helper/rest/api/v2010/api_service.go b/examples/go/go-client/helper/rest/api/v2010/api_service.go index d04084417..4b835cf10 100644 --- a/examples/go/go-client/helper/rest/api/v2010/api_service.go +++ b/examples/go/go-client/helper/rest/api/v2010/api_service.go @@ -28,6 +28,7 @@ func (c *ApiService) RequestHandler() *twilio.RequestHandler { } func NewApiService(requestHandler *twilio.RequestHandler) *ApiService { + return &ApiService{ requestHandler: requestHandler, baseURL: "https://api.twilio.com", diff --git a/examples/go/go-client/helper/rest/flex/v1/api_service.go b/examples/go/go-client/helper/rest/flex/v1/api_service.go index 79d8add73..9ceb8cd33 100644 --- a/examples/go/go-client/helper/rest/flex/v1/api_service.go +++ b/examples/go/go-client/helper/rest/flex/v1/api_service.go @@ -28,6 +28,7 @@ func (c *ApiService) RequestHandler() *twilio.RequestHandler { } func NewApiService(requestHandler *twilio.RequestHandler) *ApiService { + return &ApiService{ requestHandler: requestHandler, baseURL: "https://flex-api.twilio.com", diff --git a/examples/go/go-client/helper/rest/oauth/v2/api_service.go b/examples/go/go-client/helper/rest/oauth/v2/api_service.go index 8c9df1c36..e9b673a30 100644 --- a/examples/go/go-client/helper/rest/oauth/v2/api_service.go +++ b/examples/go/go-client/helper/rest/oauth/v2/api_service.go @@ -28,6 +28,7 @@ func (c *ApiService) RequestHandler() *twilio.RequestHandler { } func NewApiService(requestHandler *twilio.RequestHandler) *ApiService { + return &ApiService{ requestHandler: requestHandler, baseURL: "https://oauth.twilio.com", diff --git a/examples/java/src/main/java/com/twilio/rest/api/v2010/AccountReader.java b/examples/java/src/main/java/com/twilio/rest/api/v2010/AccountReader.java index 1ad9f47fb..343876cd9 100644 --- a/examples/java/src/main/java/com/twilio/rest/api/v2010/AccountReader.java +++ b/examples/java/src/main/java/com/twilio/rest/api/v2010/AccountReader.java @@ -79,7 +79,7 @@ public AccountReader setPageSize(final Integer pageSize){ public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - + public Page firstPage(final TwilioRestClient client) { String path = "/2010-04-01/Accounts.json"; @@ -103,7 +103,7 @@ private Page pageForRequest(final TwilioRestClient client, final Reques RestException restException = RestException.fromJson( response.getStream(), client.getObjectMapper()); - + if (restException == null) { throw new ApiException("Server Error, no content", response.getStatusCode()); } @@ -126,14 +126,15 @@ public Page previousPage(final Page page, final TwilioRestClie @Override public Page nextPage(final Page page, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); - return pageForRequest(client, request); + return pageForRequest(client, request); } @Override public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); + return pageForRequest(client, request); } + private void addQueryParams(final Request request) { diff --git a/examples/java/src/main/java/com/twilio/rest/flexapi/v1/credential/AwsReader.java b/examples/java/src/main/java/com/twilio/rest/flexapi/v1/credential/AwsReader.java index e95943f19..8cfc2bf1a 100644 --- a/examples/java/src/main/java/com/twilio/rest/flexapi/v1/credential/AwsReader.java +++ b/examples/java/src/main/java/com/twilio/rest/flexapi/v1/credential/AwsReader.java @@ -49,7 +49,7 @@ public AwsReader setPageSize(final Integer pageSize){ public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - + public Page firstPage(final TwilioRestClient client) { String path = "/v1/Credentials/AWS"; @@ -73,7 +73,7 @@ private Page pageForRequest(final TwilioRestClient client, final Request re RestException restException = RestException.fromJson( response.getStream(), client.getObjectMapper()); - + if (restException == null) { throw new ApiException("Server Error, no content", response.getStatusCode()); } @@ -96,14 +96,15 @@ public Page previousPage(final Page page, final TwilioRestClient clien @Override public Page nextPage(final Page page, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); - return pageForRequest(client, request); + return pageForRequest(client, request); } @Override public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); + return pageForRequest(client, request); } + private void addQueryParams(final Request request) { diff --git a/examples/java/src/main/java/com/twilio/rest/versionless/understand/AssistantReader.java b/examples/java/src/main/java/com/twilio/rest/versionless/understand/AssistantReader.java index 60f355db4..fd2816300 100644 --- a/examples/java/src/main/java/com/twilio/rest/versionless/understand/AssistantReader.java +++ b/examples/java/src/main/java/com/twilio/rest/versionless/understand/AssistantReader.java @@ -49,7 +49,7 @@ public AssistantReader setPageSize(final Integer pageSize){ public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - + public Page firstPage(final TwilioRestClient client) { String path = "/understand/Assistants"; @@ -73,7 +73,7 @@ private Page pageForRequest(final TwilioRestClient client, final Requ RestException restException = RestException.fromJson( response.getStream(), client.getObjectMapper()); - + if (restException == null) { throw new ApiException("Server Error, no content", response.getStatusCode()); } @@ -96,14 +96,15 @@ public Page previousPage(final Page page, final TwilioRest @Override public Page nextPage(final Page page, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); - return pageForRequest(client, request); + return pageForRequest(client, request); } @Override public Page getPage(final String targetUrl, final TwilioRestClient client) { Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); + return pageForRequest(client, request); } + private void addQueryParams(final Request request) { diff --git a/examples/php/src/Twilio/Rest/Api/V2010/Account/Call/FeedbackCallSummaryContext.php b/examples/php/src/Twilio/Rest/Api/V2010/Account/Call/FeedbackCallSummaryContext.php index 5ec360074..91e0fc192 100644 --- a/examples/php/src/Twilio/Rest/Api/V2010/Account/Call/FeedbackCallSummaryContext.php +++ b/examples/php/src/Twilio/Rest/Api/V2010/Account/Call/FeedbackCallSummaryContext.php @@ -22,6 +22,8 @@ use Twilio\Values; use Twilio\Version; use Twilio\InstanceContext; +use Twilio\Http\Response; +use Twilio\Metadata\ResourceMetadata; use Twilio\Serialize; @@ -55,17 +57,16 @@ public function __construct( } /** - * Update the FeedbackCallSummaryInstance + * Helper function for Update * * @param \DateTime $endDate * @param \DateTime $startDate * @param array|Options $options Optional Arguments - * @return FeedbackCallSummaryInstance Updated FeedbackCallSummaryInstance + * @return Response Updated Response * @throws TwilioException When an HTTP error occurs. */ - public function update(\DateTime $endDate, \DateTime $startDate, array $options = []): FeedbackCallSummaryInstance + private function _update(\DateTime $endDate, \DateTime $startDate, array $options = []): Response { - $options = new Values($options); $data = Values::of([ @@ -78,14 +79,53 @@ public function update(\DateTime $endDate, \DateTime $startDate, array $options ]); $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); - $payload = $this->version->update('POST', $this->uri, [], $data, $headers); + return $this->version->handleRequest('POST', $this->uri, [], $data, $headers, "update"); + } + /** + * Update the FeedbackCallSummaryInstance + * + * @param \DateTime $endDate + * @param \DateTime $startDate + * @param array|Options $options Optional Arguments + * @return FeedbackCallSummaryInstance Updated FeedbackCallSummaryInstance + * @throws TwilioException When an HTTP error occurs. + */ + public function update(\DateTime $endDate, \DateTime $startDate, array $options = []): FeedbackCallSummaryInstance + { + $response = $this->_update( $endDate, $startDate, $options); return new FeedbackCallSummaryInstance( $this->version, - $payload, + $response->getContent(), $this->solution['accountSid'], $this->solution['sid'] ); + + } + + /** + * Update the FeedbackCallSummaryInstance with Metadata + * + * @param \DateTime $endDate + * @param \DateTime $startDate + * @param array|Options $options Optional Arguments + * @return ResourceMetadata The Updated Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function updateWithMetadata(\DateTime $endDate, \DateTime $startDate, array $options = []): ResourceMetadata + { + $response = $this->_update( $endDate, $startDate, $options); + $resource = new FeedbackCallSummaryInstance( + $this->version, + $response->getContent(), + $this->solution['accountSid'], + $this->solution['sid'] + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); } diff --git a/examples/php/src/Twilio/Rest/Api/V2010/Account/CallContext.php b/examples/php/src/Twilio/Rest/Api/V2010/Account/CallContext.php index 2a013db24..22a29a4ab 100644 --- a/examples/php/src/Twilio/Rest/Api/V2010/Account/CallContext.php +++ b/examples/php/src/Twilio/Rest/Api/V2010/Account/CallContext.php @@ -22,6 +22,8 @@ use Twilio\Values; use Twilio\Version; use Twilio\InstanceContext; +use Twilio\Http\Response; +use Twilio\Metadata\ResourceMetadata; /** @@ -56,6 +58,18 @@ public function __construct( .'.json'; } + /** + * Helper function for Delete + * + * @return Response Deleted Response + * @throws TwilioException When an HTTP error occurs. + */ + private function _delete(): Response + { + $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded' ]); + return $this->version->handleRequest('DELETE', $this->uri, [], [], $headers, "delete"); + } + /** * Delete the CallInstance * @@ -64,12 +78,41 @@ public function __construct( */ public function delete(): bool { + $response = $this->_delete(); + + return true; + } - $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded' ]); - return $this->version->delete('DELETE', $this->uri, [], [], $headers); + /** + * Delete the CallInstance with Metadata + * + * @return ResourceMetadata The Deleted Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function deleteWithMetadata(): ResourceMetadata + { + $response = $this->_delete(); + + return new ResourceMetadata( + null, + $response->getStatusCode(), + $response->getHeaders() + ); } + /** + * Helper function for Fetch + * + * @return Response Fetched Response + * @throws TwilioException When an HTTP error occurs. + */ + private function _fetch(): Response + { + $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); + return $this->version->handleRequest('GET', $this->uri, [], [], $headers, "fetch"); + } + /** * Fetch the CallInstance * @@ -78,16 +121,36 @@ public function delete(): bool */ public function fetch(): CallInstance { - - $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); - $payload = $this->version->fetch('GET', $this->uri, [], [], $headers); - + $response = $this->_fetch(); return new CallInstance( $this->version, - $payload, + $response->getContent(), $this->solution['accountSid'], $this->solution['testInteger'] ); + + } + + /** + * Fetch the CallInstance with Metadata + * + * @return ResourceMetadata The Fetched Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function fetchWithMetadata(): ResourceMetadata + { + $response = $this->_fetch(); + $resource = new CallInstance( + $this->version, + $response->getContent(), + $this->solution['accountSid'], + $this->solution['testInteger'] + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); } diff --git a/examples/php/src/Twilio/Rest/Api/V2010/Account/CallList.php b/examples/php/src/Twilio/Rest/Api/V2010/Account/CallList.php index c7d1c82eb..f9069bfa1 100644 --- a/examples/php/src/Twilio/Rest/Api/V2010/Account/CallList.php +++ b/examples/php/src/Twilio/Rest/Api/V2010/Account/CallList.php @@ -22,6 +22,8 @@ use Twilio\Values; use Twilio\Version; use Twilio\InstanceContext; +use Twilio\Http\Response; +use Twilio\Metadata\ResourceMetadata; use Twilio\Serialize; use Twilio\Rest\Api\V2010\Account\Call\FeedbackCallSummaryList; @@ -57,17 +59,16 @@ public function __construct( } /** - * Create the CallInstance + * Helper function for Create * * @param string $requiredStringProperty * @param string $testMethod The HTTP method that we should use to request the `TestArrayOfUri`. * @param array|Options $options Optional Arguments - * @return CallInstance Created CallInstance + * @return Response Created Response * @throws TwilioException When an HTTP error occurs. */ - public function create(string $requiredStringProperty, string $testMethod, array $options = []): CallInstance + private function _create(string $requiredStringProperty, string $testMethod, array $options = []): Response { - $options = new Values($options); $data = Values::of([ @@ -82,13 +83,51 @@ public function create(string $requiredStringProperty, string $testMethod, array ]); $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); - $payload = $this->version->create('POST', $this->uri, [], $data, $headers); + return $this->version->handleRequest('POST', $this->uri, [], $data, $headers, "create"); + } + /** + * Create the CallInstance + * + * @param string $requiredStringProperty + * @param string $testMethod The HTTP method that we should use to request the `TestArrayOfUri`. + * @param array|Options $options Optional Arguments + * @return CallInstance Created CallInstance + * @throws TwilioException When an HTTP error occurs. + */ + public function create(string $requiredStringProperty, string $testMethod, array $options = []): CallInstance + { + $response = $this->_create( $requiredStringProperty, $testMethod, $options); return new CallInstance( $this->version, - $payload, + $response->getContent(), $this->solution['accountSid'] ); + + } + + /** + * Create the CallInstance with Metadata + * + * @param string $requiredStringProperty + * @param string $testMethod The HTTP method that we should use to request the `TestArrayOfUri`. + * @param array|Options $options Optional Arguments + * @return ResourceMetadata The Created Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function createWithMetadata(string $requiredStringProperty, string $testMethod, array $options = []): ResourceMetadata + { + $response = $this->_create( $requiredStringProperty, $testMethod, $options); + $resource = new CallInstance( + $this->version, + $response->getContent(), + $this->solution['accountSid'] + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); } diff --git a/examples/php/src/Twilio/Rest/Api/V2010/AccountContext.php b/examples/php/src/Twilio/Rest/Api/V2010/AccountContext.php index 99b8c850c..dc8c8212d 100644 --- a/examples/php/src/Twilio/Rest/Api/V2010/AccountContext.php +++ b/examples/php/src/Twilio/Rest/Api/V2010/AccountContext.php @@ -23,6 +23,8 @@ use Twilio\Values; use Twilio\Version; use Twilio\InstanceContext; +use Twilio\Http\Response; +use Twilio\Metadata\ResourceMetadata; use Twilio\Rest\Api\V2010\Account\CallList; @@ -56,6 +58,18 @@ public function __construct( .'.json'; } + /** + * Helper function for Delete + * + * @return Response Deleted Response + * @throws TwilioException When an HTTP error occurs. + */ + private function _delete(): Response + { + $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded' ]); + return $this->version->handleRequest('DELETE', $this->uri, [], [], $headers, "delete"); + } + /** * Delete the AccountInstance * @@ -64,12 +78,41 @@ public function __construct( */ public function delete(): bool { + $response = $this->_delete(); + + return true; + } - $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded' ]); - return $this->version->delete('DELETE', $this->uri, [], [], $headers); + /** + * Delete the AccountInstance with Metadata + * + * @return ResourceMetadata The Deleted Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function deleteWithMetadata(): ResourceMetadata + { + $response = $this->_delete(); + + return new ResourceMetadata( + null, + $response->getStatusCode(), + $response->getHeaders() + ); } + /** + * Helper function for Fetch + * + * @return Response Fetched Response + * @throws TwilioException When an HTTP error occurs. + */ + private function _fetch(): Response + { + $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); + return $this->version->handleRequest('GET', $this->uri, [], [], $headers, "fetch"); + } + /** * Fetch the AccountInstance * @@ -78,29 +121,47 @@ public function delete(): bool */ public function fetch(): AccountInstance { - - $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); - $payload = $this->version->fetch('GET', $this->uri, [], [], $headers); - + $response = $this->_fetch(); return new AccountInstance( $this->version, - $payload, + $response->getContent(), $this->solution['sid'] ); + + } + + /** + * Fetch the AccountInstance with Metadata + * + * @return ResourceMetadata The Fetched Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function fetchWithMetadata(): ResourceMetadata + { + $response = $this->_fetch(); + $resource = new AccountInstance( + $this->version, + $response->getContent(), + $this->solution['sid'] + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); } /** - * Update the AccountInstance + * Helper function for Update * * @param string $status * @param array|Options $options Optional Arguments - * @return AccountInstance Updated AccountInstance + * @return Response Updated Response * @throws TwilioException When an HTTP error occurs. */ - public function update(string $status, array $options = []): AccountInstance + private function _update(string $status, array $options = []): Response { - $options = new Values($options); $data = Values::of([ @@ -111,13 +172,49 @@ public function update(string $status, array $options = []): AccountInstance ]); $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); - $payload = $this->version->update('POST', $this->uri, [], $data, $headers); + return $this->version->handleRequest('POST', $this->uri, [], $data, $headers, "update"); + } + /** + * Update the AccountInstance + * + * @param string $status + * @param array|Options $options Optional Arguments + * @return AccountInstance Updated AccountInstance + * @throws TwilioException When an HTTP error occurs. + */ + public function update(string $status, array $options = []): AccountInstance + { + $response = $this->_update( $status, $options); return new AccountInstance( $this->version, - $payload, + $response->getContent(), $this->solution['sid'] ); + + } + + /** + * Update the AccountInstance with Metadata + * + * @param string $status + * @param array|Options $options Optional Arguments + * @return ResourceMetadata The Updated Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function updateWithMetadata(string $status, array $options = []): ResourceMetadata + { + $response = $this->_update( $status, $options); + $resource = new AccountInstance( + $this->version, + $response->getContent(), + $this->solution['sid'] + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); } diff --git a/examples/php/src/Twilio/Rest/Api/V2010/AccountList.php b/examples/php/src/Twilio/Rest/Api/V2010/AccountList.php index 5c505202c..25229f396 100644 --- a/examples/php/src/Twilio/Rest/Api/V2010/AccountList.php +++ b/examples/php/src/Twilio/Rest/Api/V2010/AccountList.php @@ -22,6 +22,11 @@ use Twilio\Stream; use Twilio\Values; use Twilio\Version; +use Twilio\Http\Response; +use Twilio\Metadata\ArrayMetadata; +use Twilio\Metadata\PageMetadata; +use Twilio\Metadata\ResourceMetadata; +use Twilio\Metadata\StreamMetadata; use Twilio\Serialize; @@ -45,15 +50,14 @@ public function __construct( } /** - * Create the AccountInstance + * Helper function for Create * * @param array|Options $options Optional Arguments - * @return AccountInstance Created AccountInstance + * @return Response Created Response * @throws TwilioException When an HTTP error occurs. */ - public function create(array $options = []): AccountInstance + private function _create(array $options = []): Response { - $options = new Values($options); $data = Values::of([ @@ -66,11 +70,44 @@ public function create(array $options = []): AccountInstance ]); $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' , 'X-Twilio-Webhook-Enabled' => $options['xTwilioWebhookEnabled']]); - $payload = $this->version->create('POST', $this->uri, [], $data, $headers); + return $this->version->handleRequest('POST', $this->uri, [], $data, $headers, "create"); + } + /** + * Create the AccountInstance + * + * @param array|Options $options Optional Arguments + * @return AccountInstance Created AccountInstance + * @throws TwilioException When an HTTP error occurs. + */ + public function create(array $options = []): AccountInstance + { + $response = $this->_create($options); return new AccountInstance( $this->version, - $payload + $response->getContent() + ); + + } + + /** + * Create the AccountInstance with Metadata + * + * @param array|Options $options Optional Arguments + * @return ResourceMetadata The Created Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function createWithMetadata(array $options = []): ResourceMetadata + { + $response = $this->_create($options); + $resource = new AccountInstance( + $this->version, + $response->getContent() + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() ); } @@ -96,6 +133,33 @@ public function read(array $options = [], ?int $limit = null, $pageSize = null): return \iterator_to_array($this->stream($options, $limit, $pageSize), false); } + /** + * Reads AccountInstance records from the API as a list + * Unlike stream(), this operation is eager and will load `limit` records into + * memory before returning. + * + * @param array|Options $options Optional Arguments + * @param int $limit Upper limit for the number of records to return. read() + * guarantees to never return more than limit. Default is no + * limit + * @param mixed $pageSize Number of records to fetch per request, when not set + * will use the default value of 50 records. If no + * page_size is defined but a limit is defined, read() + * will attempt to read the limit with the most + * efficient page size, i.e. min(limit, 1000) + * @return ArrayMetadata Array of results along with metadata + */ + public function readWithMetadata(array $options = [], ?int $limit = null, $pageSize = null): ArrayMetadata + { + $streamWithMetadata = $this->streamWithMetadata($options, $limit, $pageSize); + $readResponse = \iterator_to_array($streamWithMetadata, false); + return new ArrayMetadata( + $readResponse, + $streamWithMetadata->getStatusCode(), + $streamWithMetadata->getHeaders() + ); + } + /** * Streams AccountInstance records from the API as a generator stream. * This operation lazily loads records as efficiently as possible until the @@ -125,20 +189,53 @@ public function stream(array $options = [], ?int $limit = null, $pageSize = null } /** - * Retrieve a single page of AccountInstance records from the API. - * Request is executed immediately + * Streams AccountInstance records from the API as a generator stream and returns result with Metadata + * This operation lazily loads records as efficiently as possible until the + * limit + * is reached. + * The results are returned as a generator, so this operation is memory + * efficient. + * + * @param array|Options $options Optional Arguments + * @param int $limit Upper limit for the number of records to return. stream() + * guarantees to never return more than limit. Default is no + * limit + * @param mixed $pageSize Number of records to fetch per request, when not set + * will use the default value of 50 records. If no + * page_size is defined but a limit is defined, stream() + * will attempt to read the limit with the most + * efficient page size, i.e. min(limit, 1000) + * @return StreamMetadata stream of results with metadata + */ + public function streamWithMetadata(array $options = [], ?int $limit = null, $pageSize = null): StreamMetadata + { + $limits = $this->version->readLimits($limit, $pageSize); + + $pageWithMetadata = $this->pageWithMetadata($options, $limits['pageSize']); + + $stream = $this->version->stream($pageWithMetadata->getPage(), $limits['limit'], $limits['pageLimit']); + + return new StreamMetadata( + $stream, + $pageWithMetadata->getStatusCode(), + $pageWithMetadata->getHeaders() + ); + } + + /** + * Helper function for Page * * @param mixed $pageSize Number of records to return, defaults to 50 * @param string $pageToken PageToken provided by the API * @param mixed $pageNumber Page Number, this value is simply for client state - * @return AccountPage Page of AccountInstance + * @return Response Paged Response */ - public function page( + private function _page( array $options = [], $pageSize = Values::NONE, string $pageToken = Values::NONE, $pageNumber = Values::NONE - ): AccountPage + ): Response { $options = new Values($options); @@ -151,17 +248,64 @@ public function page( Serialize::iso8601DateTime($options['dateCreatedBefore']), 'DateCreated>' => Serialize::iso8601DateTime($options['dateCreatedAfter']), + 'PageToken' => $pageToken, 'Page' => $pageNumber, 'PageSize' => $pageSize, ]); $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json']); - $response = $this->version->page('GET', $this->uri, $params, [], $headers); + return $this->version->page('GET', $this->uri, $params, [], $headers); + } + + /** + * Retrieve a single page of AccountInstance records from the API. + * Request is executed immediately + * + * @param mixed $pageSize Number of records to return, defaults to 50 + * @param string $pageToken PageToken provided by the API + * @param mixed $pageNumber Page Number, this value is simply for client state + * @return AccountPage Page of AccountInstance + */ + public function page( + array $options = [], + $pageSize = Values::NONE, + string $pageToken = Values::NONE, + $pageNumber = Values::NONE + ): AccountPage + { + $response = $this->_page($options, $pageSize, $pageToken, $pageNumber); return new AccountPage($this->version, $response, $this->solution); } + /** + * Retrieve a single page of AccountInstance records with metadata + * Request is executed immediately + * + * @param mixed $pageSize Number of records to return, defaults to 50 + * @param string $pageToken PageToken provided by the API + * @param mixed $pageNumber Page Number, this value is simply for client state + * @return PageMetadata of AccountInstance + */ + public function pageWithMetadata( + array $options = [], + $pageSize = Values::NONE, + string $pageToken = Values::NONE, + $pageNumber = Values::NONE + ): PageMetadata + { + $response = $this->_page($options, $pageSize, $pageToken, $pageNumber); + + $resource = new AccountPage($this->version, $response, $this->solution); + + return new PageMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); + } + /** * Retrieve a specific page of AccountInstance records from the API. * Request is executed immediately diff --git a/examples/php/src/Twilio/Rest/FlexApi/V1/CallContext.php b/examples/php/src/Twilio/Rest/FlexApi/V1/CallContext.php index bddfbf44d..f40db9c4f 100644 --- a/examples/php/src/Twilio/Rest/FlexApi/V1/CallContext.php +++ b/examples/php/src/Twilio/Rest/FlexApi/V1/CallContext.php @@ -21,6 +21,8 @@ use Twilio\Values; use Twilio\Version; use Twilio\InstanceContext; +use Twilio\Http\Response; +use Twilio\Metadata\ResourceMetadata; class CallContext extends InstanceContext @@ -47,6 +49,18 @@ public function __construct( .''; } + /** + * Helper function for Update + * + * @return Response Updated Response + * @throws TwilioException When an HTTP error occurs. + */ + private function _update(): Response + { + $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); + return $this->version->handleRequest('POST', $this->uri, [], [], $headers, "update"); + } + /** * Update the CallInstance * @@ -55,15 +69,34 @@ public function __construct( */ public function update(): CallInstance { - - $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); - $payload = $this->version->update('POST', $this->uri, [], [], $headers); - + $response = $this->_update(); return new CallInstance( $this->version, - $payload, + $response->getContent(), $this->solution['sid'] ); + + } + + /** + * Update the CallInstance with Metadata + * + * @return ResourceMetadata The Updated Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function updateWithMetadata(): ResourceMetadata + { + $response = $this->_update(); + $resource = new CallInstance( + $this->version, + $response->getContent(), + $this->solution['sid'] + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); } diff --git a/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/Aws/HistoryContext.php b/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/Aws/HistoryContext.php index 3ebd3f4be..ee05ebd66 100644 --- a/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/Aws/HistoryContext.php +++ b/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/Aws/HistoryContext.php @@ -22,6 +22,8 @@ use Twilio\Values; use Twilio\Version; use Twilio\InstanceContext; +use Twilio\Http\Response; +use Twilio\Metadata\ResourceMetadata; use Twilio\Serialize; @@ -50,15 +52,14 @@ public function __construct( } /** - * Fetch the HistoryInstance + * Helper function for Fetch * * @param array|Options $options Optional Arguments - * @return HistoryInstance Fetched HistoryInstance + * @return Response Fetched Response * @throws TwilioException When an HTTP error occurs. */ - public function fetch(array $options = []): HistoryInstance + private function _fetch(array $options = []): Response { - $options = new Values($options); $params = Values::of([ @@ -66,13 +67,47 @@ public function fetch(array $options = []): HistoryInstance $params = \array_merge($params, Serialize::prefixedCollapsibleMap($options['addOnsData'], 'AddOns')); $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); - $payload = $this->version->fetch('GET', $this->uri, $params, [], $headers); + return $this->version->handleRequest('GET', $this->uri, $params, [], $headers, "fetch"); + } + /** + * Fetch the HistoryInstance + * + * @param array|Options $options Optional Arguments + * @return HistoryInstance Fetched HistoryInstance + * @throws TwilioException When an HTTP error occurs. + */ + public function fetch(array $options = []): HistoryInstance + { + $response = $this->_fetch($options); return new HistoryInstance( $this->version, - $payload, + $response->getContent(), $this->solution['sid'] ); + + } + + /** + * Fetch the HistoryInstance with Metadata + * + * @param array|Options $options Optional Arguments + * @return ResourceMetadata The Fetched Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function fetchWithMetadata(array $options = []): ResourceMetadata + { + $response = $this->_fetch($options); + $resource = new HistoryInstance( + $this->version, + $response->getContent(), + $this->solution['sid'] + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); } diff --git a/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/AwsContext.php b/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/AwsContext.php index 4c3fe07b4..e33fb4e13 100644 --- a/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/AwsContext.php +++ b/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/AwsContext.php @@ -23,6 +23,8 @@ use Twilio\Values; use Twilio\Version; use Twilio\InstanceContext; +use Twilio\Http\Response; +use Twilio\Metadata\ResourceMetadata; use Twilio\Serialize; use Twilio\Rest\FlexApi\V1\Credential\Aws\HistoryList; @@ -57,6 +59,18 @@ public function __construct( .''; } + /** + * Helper function for Delete + * + * @return Response Deleted Response + * @throws TwilioException When an HTTP error occurs. + */ + private function _delete(): Response + { + $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded' ]); + return $this->version->handleRequest('DELETE', $this->uri, [], [], $headers, "delete"); + } + /** * Delete the AwsInstance * @@ -65,12 +79,41 @@ public function __construct( */ public function delete(): bool { + $response = $this->_delete(); + + return true; + } - $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded' ]); - return $this->version->delete('DELETE', $this->uri, [], [], $headers); + /** + * Delete the AwsInstance with Metadata + * + * @return ResourceMetadata The Deleted Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function deleteWithMetadata(): ResourceMetadata + { + $response = $this->_delete(); + + return new ResourceMetadata( + null, + $response->getStatusCode(), + $response->getHeaders() + ); } + /** + * Helper function for Fetch + * + * @return Response Fetched Response + * @throws TwilioException When an HTTP error occurs. + */ + private function _fetch(): Response + { + $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); + return $this->version->handleRequest('GET', $this->uri, [], [], $headers, "fetch"); + } + /** * Fetch the AwsInstance * @@ -79,28 +122,46 @@ public function delete(): bool */ public function fetch(): AwsInstance { - - $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); - $payload = $this->version->fetch('GET', $this->uri, [], [], $headers); - + $response = $this->_fetch(); return new AwsInstance( $this->version, - $payload, + $response->getContent(), $this->solution['sid'] ); + + } + + /** + * Fetch the AwsInstance with Metadata + * + * @return ResourceMetadata The Fetched Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function fetchWithMetadata(): ResourceMetadata + { + $response = $this->_fetch(); + $resource = new AwsInstance( + $this->version, + $response->getContent(), + $this->solution['sid'] + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); } /** - * Update the AwsInstance + * Helper function for Update * * @param array|Options $options Optional Arguments - * @return AwsInstance Updated AwsInstance + * @return Response Updated Response * @throws TwilioException When an HTTP error occurs. */ - public function update(array $options = []): AwsInstance + private function _update(array $options = []): Response { - $options = new Values($options); $data = Values::of([ @@ -111,13 +172,47 @@ public function update(array $options = []): AwsInstance ]); $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); - $payload = $this->version->update('POST', $this->uri, [], $data, $headers); + return $this->version->handleRequest('POST', $this->uri, [], $data, $headers, "update"); + } + /** + * Update the AwsInstance + * + * @param array|Options $options Optional Arguments + * @return AwsInstance Updated AwsInstance + * @throws TwilioException When an HTTP error occurs. + */ + public function update(array $options = []): AwsInstance + { + $response = $this->_update($options); return new AwsInstance( $this->version, - $payload, + $response->getContent(), $this->solution['sid'] ); + + } + + /** + * Update the AwsInstance with Metadata + * + * @param array|Options $options Optional Arguments + * @return ResourceMetadata The Updated Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function updateWithMetadata(array $options = []): ResourceMetadata + { + $response = $this->_update($options); + $resource = new AwsInstance( + $this->version, + $response->getContent(), + $this->solution['sid'] + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); } diff --git a/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/AwsList.php b/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/AwsList.php index dfc67fffe..1ad01ca35 100644 --- a/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/AwsList.php +++ b/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/AwsList.php @@ -20,6 +20,10 @@ use Twilio\Stream; use Twilio\Values; use Twilio\Version; +use Twilio\Http\Response; +use Twilio\Metadata\ArrayMetadata; +use Twilio\Metadata\PageMetadata; +use Twilio\Metadata\StreamMetadata; class AwsList extends ListResource @@ -61,6 +65,32 @@ public function read(?int $limit = null, $pageSize = null): array return \iterator_to_array($this->stream($limit, $pageSize), false); } + /** + * Reads AwsInstance records from the API as a list + * Unlike stream(), this operation is eager and will load `limit` records into + * memory before returning. + * + * @param int $limit Upper limit for the number of records to return. read() + * guarantees to never return more than limit. Default is no + * limit + * @param mixed $pageSize Number of records to fetch per request, when not set + * will use the default value of 50 records. If no + * page_size is defined but a limit is defined, read() + * will attempt to read the limit with the most + * efficient page size, i.e. min(limit, 1000) + * @return ArrayMetadata Array of results along with metadata + */ + public function readWithMetadata(?int $limit = null, $pageSize = null): ArrayMetadata + { + $streamWithMetadata = $this->streamWithMetadata($limit, $pageSize); + $readResponse = \iterator_to_array($streamWithMetadata, false); + return new ArrayMetadata( + $readResponse, + $streamWithMetadata->getStatusCode(), + $streamWithMetadata->getHeaders() + ); + } + /** * Streams AwsInstance records from the API as a generator stream. * This operation lazily loads records as efficiently as possible until the @@ -89,19 +119,51 @@ public function stream(?int $limit = null, $pageSize = null): Stream } /** - * Retrieve a single page of AwsInstance records from the API. - * Request is executed immediately + * Streams AwsInstance records from the API as a generator stream and returns result with Metadata + * This operation lazily loads 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 $limit Upper limit for the number of records to return. stream() + * guarantees to never return more than limit. Default is no + * limit + * @param mixed $pageSize Number of records to fetch per request, when not set + * will use the default value of 50 records. If no + * page_size is defined but a limit is defined, stream() + * will attempt to read the limit with the most + * efficient page size, i.e. min(limit, 1000) + * @return StreamMetadata stream of results with metadata + */ + public function streamWithMetadata(?int $limit = null, $pageSize = null): StreamMetadata + { + $limits = $this->version->readLimits($limit, $pageSize); + + $pageWithMetadata = $this->pageWithMetadata($limits['pageSize']); + + $stream = $this->version->stream($pageWithMetadata->getPage(), $limits['limit'], $limits['pageLimit']); + + return new StreamMetadata( + $stream, + $pageWithMetadata->getStatusCode(), + $pageWithMetadata->getHeaders() + ); + } + + /** + * Helper function for Page * * @param mixed $pageSize Number of records to return, defaults to 50 * @param string $pageToken PageToken provided by the API * @param mixed $pageNumber Page Number, this value is simply for client state - * @return AwsPage Page of AwsInstance + * @return Response Paged Response */ - public function page( + private function _page( $pageSize = Values::NONE, string $pageToken = Values::NONE, $pageNumber = Values::NONE - ): AwsPage + ): Response { $params = Values::of([ @@ -111,11 +173,55 @@ public function page( ]); $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json']); - $response = $this->version->page('GET', $this->uri, $params, [], $headers); + return $this->version->page('GET', $this->uri, $params, [], $headers); + } + + /** + * Retrieve a single page of AwsInstance records from the API. + * Request is executed immediately + * + * @param mixed $pageSize Number of records to return, defaults to 50 + * @param string $pageToken PageToken provided by the API + * @param mixed $pageNumber Page Number, this value is simply for client state + * @return AwsPage Page of AwsInstance + */ + public function page( + $pageSize = Values::NONE, + string $pageToken = Values::NONE, + $pageNumber = Values::NONE + ): AwsPage + { + $response = $this->_page( $pageSize, $pageToken, $pageNumber); return new AwsPage($this->version, $response, $this->solution); } + /** + * Retrieve a single page of AwsInstance records with metadata + * Request is executed immediately + * + * @param mixed $pageSize Number of records to return, defaults to 50 + * @param string $pageToken PageToken provided by the API + * @param mixed $pageNumber Page Number, this value is simply for client state + * @return PageMetadata of AwsInstance + */ + public function pageWithMetadata( + $pageSize = Values::NONE, + string $pageToken = Values::NONE, + $pageNumber = Values::NONE + ): PageMetadata + { + $response = $this->_page( $pageSize, $pageToken, $pageNumber); + + $resource = new AwsPage($this->version, $response, $this->solution); + + return new PageMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); + } + /** * Retrieve a specific page of AwsInstance records from the API. * Request is executed immediately diff --git a/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/NewCredentialsList.php b/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/NewCredentialsList.php index da23eda47..2ebebc18c 100644 --- a/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/NewCredentialsList.php +++ b/examples/php/src/Twilio/Rest/FlexApi/V1/Credential/NewCredentialsList.php @@ -21,6 +21,8 @@ use Twilio\Options; use Twilio\Values; use Twilio\Version; +use Twilio\Http\Response; +use Twilio\Metadata\ResourceMetadata; use Twilio\Serialize; @@ -44,16 +46,15 @@ public function __construct( } /** - * Create the NewCredentialsInstance + * Helper function for Create * * @param string $testString * @param array|Options $options Optional Arguments - * @return NewCredentialsInstance Created NewCredentialsInstance + * @return Response Created Response * @throws TwilioException When an HTTP error occurs. */ - public function create(string $testString, array $options = []): NewCredentialsInstance + private function _create(string $testString, array $options = []): Response { - $options = new Values($options); $data = Values::of([ @@ -94,11 +95,46 @@ public function create(string $testString, array $options = []): NewCredentialsI ]); $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); - $payload = $this->version->create('POST', $this->uri, [], $data, $headers); + return $this->version->handleRequest('POST', $this->uri, [], $data, $headers, "create"); + } + /** + * Create the NewCredentialsInstance + * + * @param string $testString + * @param array|Options $options Optional Arguments + * @return NewCredentialsInstance Created NewCredentialsInstance + * @throws TwilioException When an HTTP error occurs. + */ + public function create(string $testString, array $options = []): NewCredentialsInstance + { + $response = $this->_create( $testString, $options); return new NewCredentialsInstance( $this->version, - $payload + $response->getContent() + ); + + } + + /** + * Create the NewCredentialsInstance with Metadata + * + * @param string $testString + * @param array|Options $options Optional Arguments + * @return ResourceMetadata The Created Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function createWithMetadata(string $testString, array $options = []): ResourceMetadata + { + $response = $this->_create( $testString, $options); + $resource = new NewCredentialsInstance( + $this->version, + $response->getContent() + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() ); } diff --git a/examples/php/src/Twilio/Rest/Oauth/V2/TokenList.php b/examples/php/src/Twilio/Rest/Oauth/V2/TokenList.php index 96dfdbc8a..7ebf07b8e 100644 --- a/examples/php/src/Twilio/Rest/Oauth/V2/TokenList.php +++ b/examples/php/src/Twilio/Rest/Oauth/V2/TokenList.php @@ -21,6 +21,8 @@ use Twilio\Options; use Twilio\Values; use Twilio\Version; +use Twilio\Http\Response; +use Twilio\Metadata\ResourceMetadata; class TokenList extends ListResource @@ -43,15 +45,14 @@ public function __construct( } /** - * Create the TokenInstance + * Helper function for Create * * @param array|Options $options Optional Arguments - * @return TokenInstance Created TokenInstance + * @return Response Created Response * @throws TwilioException When an HTTP error occurs. */ - public function create(array $options = []): TokenInstance + private function _create(array $options = []): Response { - $options = new Values($options); $data = Values::of([ @@ -74,11 +75,44 @@ public function create(array $options = []): TokenInstance ]); $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); - $payload = $this->version->create('POST', $this->uri, [], $data, $headers); + return $this->version->handleRequest('POST', $this->uri, [], $data, $headers, "create"); + } + /** + * Create the TokenInstance + * + * @param array|Options $options Optional Arguments + * @return TokenInstance Created TokenInstance + * @throws TwilioException When an HTTP error occurs. + */ + public function create(array $options = []): TokenInstance + { + $response = $this->_create($options); return new TokenInstance( $this->version, - $payload + $response->getContent() + ); + + } + + /** + * Create the TokenInstance with Metadata + * + * @param array|Options $options Optional Arguments + * @return ResourceMetadata The Created Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function createWithMetadata(array $options = []): ResourceMetadata + { + $response = $this->_create($options); + $resource = new TokenInstance( + $this->version, + $response->getContent() + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() ); } diff --git a/examples/php/src/Twilio/Rest/Versionless/DeployedDevices/FleetContext.php b/examples/php/src/Twilio/Rest/Versionless/DeployedDevices/FleetContext.php index c878f59f1..49da77905 100644 --- a/examples/php/src/Twilio/Rest/Versionless/DeployedDevices/FleetContext.php +++ b/examples/php/src/Twilio/Rest/Versionless/DeployedDevices/FleetContext.php @@ -21,6 +21,8 @@ use Twilio\Values; use Twilio\Version; use Twilio\InstanceContext; +use Twilio\Http\Response; +use Twilio\Metadata\ResourceMetadata; class FleetContext extends InstanceContext @@ -47,6 +49,18 @@ public function __construct( .''; } + /** + * Helper function for Fetch + * + * @return Response Fetched Response + * @throws TwilioException When an HTTP error occurs. + */ + private function _fetch(): Response + { + $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); + return $this->version->handleRequest('GET', $this->uri, [], [], $headers, "fetch"); + } + /** * Fetch the FleetInstance * @@ -55,15 +69,34 @@ public function __construct( */ public function fetch(): FleetInstance { - - $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); - $payload = $this->version->fetch('GET', $this->uri, [], [], $headers); - + $response = $this->_fetch(); return new FleetInstance( $this->version, - $payload, + $response->getContent(), $this->solution['sid'] ); + + } + + /** + * Fetch the FleetInstance with Metadata + * + * @return ResourceMetadata The Fetched Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function fetchWithMetadata(): ResourceMetadata + { + $response = $this->_fetch(); + $resource = new FleetInstance( + $this->version, + $response->getContent(), + $this->solution['sid'] + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); } diff --git a/examples/php/src/Twilio/Rest/Versionless/DeployedDevices/FleetList.php b/examples/php/src/Twilio/Rest/Versionless/DeployedDevices/FleetList.php index 1c1902c5d..570139911 100644 --- a/examples/php/src/Twilio/Rest/Versionless/DeployedDevices/FleetList.php +++ b/examples/php/src/Twilio/Rest/Versionless/DeployedDevices/FleetList.php @@ -21,6 +21,8 @@ use Twilio\Options; use Twilio\Values; use Twilio\Version; +use Twilio\Http\Response; +use Twilio\Metadata\ResourceMetadata; class FleetList extends ListResource @@ -43,15 +45,14 @@ public function __construct( } /** - * Create the FleetInstance + * Helper function for Create * * @param array|Options $options Optional Arguments - * @return FleetInstance Created FleetInstance + * @return Response Created Response * @throws TwilioException When an HTTP error occurs. */ - public function create(array $options = []): FleetInstance + private function _create(array $options = []): Response { - $options = new Values($options); $data = Values::of([ @@ -60,11 +61,44 @@ public function create(array $options = []): FleetInstance ]); $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' ]); - $payload = $this->version->create('POST', $this->uri, [], $data, $headers); + return $this->version->handleRequest('POST', $this->uri, [], $data, $headers, "create"); + } + /** + * Create the FleetInstance + * + * @param array|Options $options Optional Arguments + * @return FleetInstance Created FleetInstance + * @throws TwilioException When an HTTP error occurs. + */ + public function create(array $options = []): FleetInstance + { + $response = $this->_create($options); return new FleetInstance( $this->version, - $payload + $response->getContent() + ); + + } + + /** + * Create the FleetInstance with Metadata + * + * @param array|Options $options Optional Arguments + * @return ResourceMetadata The Created Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function createWithMetadata(array $options = []): ResourceMetadata + { + $response = $this->_create($options); + $resource = new FleetInstance( + $this->version, + $response->getContent() + ); + return new ResourceMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() ); } diff --git a/examples/php/src/Twilio/Rest/Versionless/Understand/AssistantList.php b/examples/php/src/Twilio/Rest/Versionless/Understand/AssistantList.php index 2c5ad57d6..eb1792de6 100644 --- a/examples/php/src/Twilio/Rest/Versionless/Understand/AssistantList.php +++ b/examples/php/src/Twilio/Rest/Versionless/Understand/AssistantList.php @@ -20,6 +20,10 @@ use Twilio\Stream; use Twilio\Values; use Twilio\Version; +use Twilio\Http\Response; +use Twilio\Metadata\ArrayMetadata; +use Twilio\Metadata\PageMetadata; +use Twilio\Metadata\StreamMetadata; class AssistantList extends ListResource @@ -61,6 +65,32 @@ public function read(?int $limit = null, $pageSize = null): array return \iterator_to_array($this->stream($limit, $pageSize), false); } + /** + * Reads AssistantInstance records from the API as a list + * Unlike stream(), this operation is eager and will load `limit` records into + * memory before returning. + * + * @param int $limit Upper limit for the number of records to return. read() + * guarantees to never return more than limit. Default is no + * limit + * @param mixed $pageSize Number of records to fetch per request, when not set + * will use the default value of 50 records. If no + * page_size is defined but a limit is defined, read() + * will attempt to read the limit with the most + * efficient page size, i.e. min(limit, 1000) + * @return ArrayMetadata Array of results along with metadata + */ + public function readWithMetadata(?int $limit = null, $pageSize = null): ArrayMetadata + { + $streamWithMetadata = $this->streamWithMetadata($limit, $pageSize); + $readResponse = \iterator_to_array($streamWithMetadata, false); + return new ArrayMetadata( + $readResponse, + $streamWithMetadata->getStatusCode(), + $streamWithMetadata->getHeaders() + ); + } + /** * Streams AssistantInstance records from the API as a generator stream. * This operation lazily loads records as efficiently as possible until the @@ -89,19 +119,51 @@ public function stream(?int $limit = null, $pageSize = null): Stream } /** - * Retrieve a single page of AssistantInstance records from the API. - * Request is executed immediately + * Streams AssistantInstance records from the API as a generator stream and returns result with Metadata + * This operation lazily loads 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 $limit Upper limit for the number of records to return. stream() + * guarantees to never return more than limit. Default is no + * limit + * @param mixed $pageSize Number of records to fetch per request, when not set + * will use the default value of 50 records. If no + * page_size is defined but a limit is defined, stream() + * will attempt to read the limit with the most + * efficient page size, i.e. min(limit, 1000) + * @return StreamMetadata stream of results with metadata + */ + public function streamWithMetadata(?int $limit = null, $pageSize = null): StreamMetadata + { + $limits = $this->version->readLimits($limit, $pageSize); + + $pageWithMetadata = $this->pageWithMetadata($limits['pageSize']); + + $stream = $this->version->stream($pageWithMetadata->getPage(), $limits['limit'], $limits['pageLimit']); + + return new StreamMetadata( + $stream, + $pageWithMetadata->getStatusCode(), + $pageWithMetadata->getHeaders() + ); + } + + /** + * Helper function for Page * * @param mixed $pageSize Number of records to return, defaults to 50 * @param string $pageToken PageToken provided by the API * @param mixed $pageNumber Page Number, this value is simply for client state - * @return AssistantPage Page of AssistantInstance + * @return Response Paged Response */ - public function page( + private function _page( $pageSize = Values::NONE, string $pageToken = Values::NONE, $pageNumber = Values::NONE - ): AssistantPage + ): Response { $params = Values::of([ @@ -111,11 +173,55 @@ public function page( ]); $headers = Values::of(['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json']); - $response = $this->version->page('GET', $this->uri, $params, [], $headers); + return $this->version->page('GET', $this->uri, $params, [], $headers); + } + + /** + * Retrieve a single page of AssistantInstance records from the API. + * Request is executed immediately + * + * @param mixed $pageSize Number of records to return, defaults to 50 + * @param string $pageToken PageToken provided by the API + * @param mixed $pageNumber Page Number, this value is simply for client state + * @return AssistantPage Page of AssistantInstance + */ + public function page( + $pageSize = Values::NONE, + string $pageToken = Values::NONE, + $pageNumber = Values::NONE + ): AssistantPage + { + $response = $this->_page( $pageSize, $pageToken, $pageNumber); return new AssistantPage($this->version, $response, $this->solution); } + /** + * Retrieve a single page of AssistantInstance records with metadata + * Request is executed immediately + * + * @param mixed $pageSize Number of records to return, defaults to 50 + * @param string $pageToken PageToken provided by the API + * @param mixed $pageNumber Page Number, this value is simply for client state + * @return PageMetadata of AssistantInstance + */ + public function pageWithMetadata( + $pageSize = Values::NONE, + string $pageToken = Values::NONE, + $pageNumber = Values::NONE + ): PageMetadata + { + $response = $this->_page( $pageSize, $pageToken, $pageNumber); + + $resource = new AssistantPage($this->version, $response, $this->solution); + + return new PageMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); + } + /** * Retrieve a specific page of AssistantInstance records from the API. * Request is executed immediately diff --git a/examples/python/twilio/rest/api/v2010/account/__init__.py b/examples/python/twilio/rest/api/v2010/account/__init__.py index beee13fcf..bdb557d8d 100644 --- a/examples/python/twilio/rest/api/v2010/account/__init__.py +++ b/examples/python/twilio/rest/api/v2010/account/__init__.py @@ -16,6 +16,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 @@ -138,6 +139,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AccountInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info() + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AccountInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async() + def fetch(self) -> "AccountInstance": """ Fetch the AccountInstance @@ -156,6 +175,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, status: "AccountInstance.Status", @@ -192,6 +229,42 @@ async def update_async( pause_behavior=pause_behavior, ) + def update_with_http_info( + self, + status: "AccountInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the AccountInstance with HTTP info + + :param status: + :param pause_behavior: + + :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: "AccountInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AccountInstance with HTTP info + + :param status: + :param pause_behavior: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + status=status, + pause_behavior=pause_behavior, + ) + @property def calls(self) -> CallList: """ @@ -295,18 +368,16 @@ async def fetch_async(self) -> AccountInstance: sid=self._solution["sid"], ) - def update( + def _update( self, status: "AccountInstance.Status", pause_behavior: Union[str, object] = values.unset, - ) -> AccountInstance: + ) -> tuple: """ - Update the AccountInstance - - :param status: - :param pause_behavior: + Internal helper for update operation - :returns: The updated AccountInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -321,25 +392,56 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return AccountInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, status: "AccountInstance.Status", pause_behavior: Union[str, object] = values.unset, ) -> AccountInstance: """ - Asynchronous coroutine to update the AccountInstance + Update the AccountInstance :param status: :param pause_behavior: :returns: The updated AccountInstance """ + payload, _, _ = self._update(status=status, pause_behavior=pause_behavior) + return AccountInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + status: "AccountInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the AccountInstance and return response metadata + + :param status: + :param pause_behavior: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + status=status, pause_behavior=pause_behavior + ) + instance = AccountInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + status: "AccountInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -353,12 +455,47 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + status: "AccountInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> AccountInstance: + """ + Asynchronous coroutine to update the AccountInstance + + :param status: + :param pause_behavior: + + :returns: The updated AccountInstance + """ + payload, _, _ = await self._update_async( + status=status, pause_behavior=pause_behavior + ) return AccountInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + status: "AccountInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AccountInstance and return response metadata + + :param status: + :param pause_behavior: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + status=status, pause_behavior=pause_behavior + ) + instance = AccountInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def calls(self) -> CallList: """ @@ -411,7 +548,7 @@ def __init__(self, version: Version): self._uri = "/Accounts.json" - def create( + def _create( self, x_twilio_webhook_enabled: Union[ "AccountInstance.XTwilioWebhookEnabled", object @@ -419,16 +556,12 @@ def create( recording_status_callback: Union[str, object] = values.unset, recording_status_callback_event: Union[List[str], object] = values.unset, twiml: Union[str, object] = values.unset, - ) -> AccountInstance: + ) -> tuple: """ - Create the AccountInstance - - :param x_twilio_webhook_enabled: - :param recording_status_callback: - :param recording_status_callback_event: - :param twiml: + Internal helper for create operation - :returns: The created AccountInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -451,13 +584,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return AccountInstance(self._version, payload) - - async def create_async( + def create( self, x_twilio_webhook_enabled: Union[ "AccountInstance.XTwilioWebhookEnabled", object @@ -467,7 +598,7 @@ async def create_async( twiml: Union[str, object] = values.unset, ) -> AccountInstance: """ - Asynchronously create the AccountInstance + Create the AccountInstance :param x_twilio_webhook_enabled: :param recording_status_callback: @@ -476,6 +607,57 @@ async def create_async( :returns: The created AccountInstance """ + payload, _, _ = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + recording_status_callback=recording_status_callback, + recording_status_callback_event=recording_status_callback_event, + twiml=twiml, + ) + return AccountInstance(self._version, payload) + + def create_with_http_info( + self, + x_twilio_webhook_enabled: Union[ + "AccountInstance.XTwilioWebhookEnabled", object + ] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + twiml: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the AccountInstance and return response metadata + + :param x_twilio_webhook_enabled: + :param recording_status_callback: + :param recording_status_callback_event: + :param twiml: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + recording_status_callback=recording_status_callback, + recording_status_callback_event=recording_status_callback_event, + twiml=twiml, + ) + instance = AccountInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + x_twilio_webhook_enabled: Union[ + "AccountInstance.XTwilioWebhookEnabled", object + ] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + twiml: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -497,12 +679,65 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "AccountInstance.XTwilioWebhookEnabled", object + ] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + twiml: Union[str, object] = values.unset, + ) -> AccountInstance: + """ + Asynchronously create the AccountInstance + + :param x_twilio_webhook_enabled: + :param recording_status_callback: + :param recording_status_callback_event: + :param twiml: + + :returns: The created AccountInstance + """ + payload, _, _ = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + recording_status_callback=recording_status_callback, + recording_status_callback_event=recording_status_callback_event, + twiml=twiml, + ) return AccountInstance(self._version, payload) + async def create_with_http_info_async( + self, + x_twilio_webhook_enabled: Union[ + "AccountInstance.XTwilioWebhookEnabled", object + ] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + twiml: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the AccountInstance and return response metadata + + :param x_twilio_webhook_enabled: + :param recording_status_callback: + :param recording_status_callback_event: + :param twiml: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + recording_status_callback=recording_status_callback, + recording_status_callback_event=recording_status_callback_event, + twiml=twiml, + ) + instance = AccountInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, date_created: Union[datetime, object] = values.unset, @@ -581,6 +816,82 @@ 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_test: Union[date, 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 AccountInstance and returns headers from first page + + + :param datetime date_created: + :param date date_test: + :param datetime date_created_before: + :param datetime date_created_after: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple 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_test=date_test, + 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_test: Union[date, 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 AccountInstance and returns headers from first page + + + :param datetime date_created: + :param date date_test: + :param datetime date_created_before: + :param datetime date_created_after: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, 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_test=date_test, + 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, @@ -658,6 +969,80 @@ async def list_async( ) ] + def list_with_http_info( + self, + date_created: Union[datetime, object] = values.unset, + date_test: Union[date, 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 AccountInstance and returns headers from first page + + + :param datetime date_created: + :param date date_test: + :param datetime date_created_before: + :param datetime date_created_after: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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_test=date_test, + 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_test: Union[date, 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 AccountInstance and returns headers from first page + + + :param datetime date_created: + :param date date_test: + :param datetime date_created_before: + :param datetime date_created_after: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. 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_test=date_test, + 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, @@ -748,6 +1133,102 @@ async def page_async( ) return AccountPage(self._version, response) + def page_with_http_info( + self, + date_created: Union[datetime, object] = values.unset, + date_test: Union[date, 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: + :param date_test: + :param date_created_before: + :param date_created_after: + :param page_token: PageToken provided by the API + :param page_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( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "Date.Test": serialize.iso8601_date(date_test), + "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 = AccountPage(self._version, response) + 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_test: Union[date, 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: + :param date_test: + :param date_created_before: + :param date_created_after: + :param page_token: PageToken provided by the API + :param page_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( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "Date.Test": serialize.iso8601_date(date_test), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + ( + response, + status_code, + response_headers, + ) = await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = 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/examples/python/twilio/rest/api/v2010/account/call/__init__.py b/examples/python/twilio/rest/api/v2010/account/call/__init__.py index 6a9ea2884..c43126abc 100644 --- a/examples/python/twilio/rest/api/v2010/account/call/__init__.py +++ b/examples/python/twilio/rest/api/v2010/account/call/__init__.py @@ -16,6 +16,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 @@ -142,6 +143,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 @@ -160,6 +179,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 __repr__(self) -> str: """ Provide a friendly representation @@ -289,22 +326,18 @@ def __init__(self, version: Version, account_sid: str): self._feedback_call_summary: Optional[FeedbackCallSummaryList] = None - def create( + def _create( self, required_string_property: str, test_method: str, test_array_of_strings: Union[List[str], object] = values.unset, test_array_of_uri: Union[List[str], object] = values.unset, - ) -> CallInstance: + ) -> tuple: """ - Create the CallInstance + Internal helper for create operation - :param required_string_property: - :param test_method: The HTTP method that we should use to request the `TestArrayOfUri`. - :param test_array_of_strings: - :param test_array_of_uri: - - :returns: The created CallInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -321,30 +354,77 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create( + self, + required_string_property: str, + test_method: str, + test_array_of_strings: Union[List[str], object] = values.unset, + test_array_of_uri: Union[List[str], object] = values.unset, + ) -> CallInstance: + """ + Create the CallInstance + + :param required_string_property: + :param test_method: The HTTP method that we should use to request the `TestArrayOfUri`. + :param test_array_of_strings: + :param test_array_of_uri: + + :returns: The created CallInstance + """ + payload, _, _ = self._create( + required_string_property=required_string_property, + test_method=test_method, + test_array_of_strings=test_array_of_strings, + test_array_of_uri=test_array_of_uri, + ) return CallInstance( self._version, payload, account_sid=self._solution["account_sid"] ) - async def create_async( + def create_with_http_info( self, required_string_property: str, test_method: str, test_array_of_strings: Union[List[str], object] = values.unset, test_array_of_uri: Union[List[str], object] = values.unset, - ) -> CallInstance: + ) -> ApiResponse: """ - Asynchronously create the CallInstance + Create the CallInstance and return response metadata :param required_string_property: :param test_method: The HTTP method that we should use to request the `TestArrayOfUri`. :param test_array_of_strings: :param test_array_of_uri: - :returns: The created CallInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + required_string_property=required_string_property, + test_method=test_method, + test_array_of_strings=test_array_of_strings, + test_array_of_uri=test_array_of_uri, + ) + 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, + required_string_property: str, + test_method: str, + test_array_of_strings: Union[List[str], object] = values.unset, + test_array_of_uri: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -361,14 +441,65 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + required_string_property: str, + test_method: str, + test_array_of_strings: Union[List[str], object] = values.unset, + test_array_of_uri: Union[List[str], object] = values.unset, + ) -> CallInstance: + """ + Asynchronously create the CallInstance + + :param required_string_property: + :param test_method: The HTTP method that we should use to request the `TestArrayOfUri`. + :param test_array_of_strings: + :param test_array_of_uri: + + :returns: The created CallInstance + """ + payload, _, _ = await self._create_async( + required_string_property=required_string_property, + test_method=test_method, + test_array_of_strings=test_array_of_strings, + test_array_of_uri=test_array_of_uri, + ) return CallInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + async def create_with_http_info_async( + self, + required_string_property: str, + test_method: str, + test_array_of_strings: Union[List[str], object] = values.unset, + test_array_of_uri: Union[List[str], object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CallInstance and return response metadata + + :param required_string_property: + :param test_method: The HTTP method that we should use to request the `TestArrayOfUri`. + :param test_array_of_strings: + :param test_array_of_uri: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + required_string_property=required_string_property, + test_method=test_method, + test_array_of_strings=test_array_of_strings, + test_array_of_uri=test_array_of_uri, + ) + instance = CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def feedback_call_summary(self) -> FeedbackCallSummaryList: """ diff --git a/examples/python/twilio/rest/api/v2010/account/call/feedback_call_summary.py b/examples/python/twilio/rest/api/v2010/account/call/feedback_call_summary.py index 779c9ec62..d590c5947 100644 --- a/examples/python/twilio/rest/api/v2010/account/call/feedback_call_summary.py +++ b/examples/python/twilio/rest/api/v2010/account/call/feedback_call_summary.py @@ -16,6 +16,7 @@ from datetime import date, 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 @@ -164,6 +165,48 @@ async def update_async( account_sid=account_sid, ) + def update_with_http_info( + self, + end_date: date, + start_date: date, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the FeedbackCallSummaryInstance with HTTP info + + :param end_date: + :param start_date: + :param account_sid: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + end_date=end_date, + start_date=start_date, + account_sid=account_sid, + ) + + async def update_with_http_info_async( + self, + end_date: date, + start_date: date, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FeedbackCallSummaryInstance with HTTP info + + :param end_date: + :param start_date: + :param account_sid: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + end_date=end_date, + start_date=start_date, + account_sid=account_sid, + ) + def __repr__(self) -> str: """ Provide a friendly representation @@ -194,20 +237,17 @@ def __init__(self, version: Version, account_sid: str, sid: str): **self._solution ) - def update( + def _update( self, end_date: date, start_date: date, account_sid: Union[str, object] = values.unset, - ) -> FeedbackCallSummaryInstance: + ) -> tuple: """ - Update the FeedbackCallSummaryInstance + Internal helper for update operation - :param end_date: - :param start_date: - :param account_sid: - - :returns: The updated FeedbackCallSummaryInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -223,10 +263,28 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def update( + self, + end_date: date, + start_date: date, + account_sid: Union[str, object] = values.unset, + ) -> FeedbackCallSummaryInstance: + """ + Update the FeedbackCallSummaryInstance + + :param end_date: + :param start_date: + :param account_sid: + + :returns: The updated FeedbackCallSummaryInstance + """ + payload, _, _ = self._update( + end_date=end_date, start_date=start_date, account_sid=account_sid + ) return FeedbackCallSummaryInstance( self._version, payload, @@ -234,20 +292,43 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, end_date: date, start_date: date, account_sid: Union[str, object] = values.unset, - ) -> FeedbackCallSummaryInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the FeedbackCallSummaryInstance + Update the FeedbackCallSummaryInstance and return response metadata :param end_date: :param start_date: :param account_sid: - :returns: The updated FeedbackCallSummaryInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + end_date=end_date, start_date=start_date, account_sid=account_sid + ) + instance = FeedbackCallSummaryInstance( + 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, + end_date: date, + start_date: date, + account_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -263,10 +344,28 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + end_date: date, + start_date: date, + account_sid: Union[str, object] = values.unset, + ) -> FeedbackCallSummaryInstance: + """ + Asynchronous coroutine to update the FeedbackCallSummaryInstance + + :param end_date: + :param start_date: + :param account_sid: + + :returns: The updated FeedbackCallSummaryInstance + """ + payload, _, _ = await self._update_async( + end_date=end_date, start_date=start_date, account_sid=account_sid + ) return FeedbackCallSummaryInstance( self._version, payload, @@ -274,6 +373,32 @@ async def update_async( sid=self._solution["sid"], ) + async def update_with_http_info_async( + self, + end_date: date, + start_date: date, + account_sid: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the FeedbackCallSummaryInstance and return response metadata + + :param end_date: + :param start_date: + :param account_sid: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + end_date=end_date, start_date=start_date, account_sid=account_sid + ) + instance = FeedbackCallSummaryInstance( + 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 diff --git a/examples/python/twilio/rest/flex_api/v1/call.py b/examples/python/twilio/rest/flex_api/v1/call.py index 4eb4fc989..183b886a2 100644 --- a/examples/python/twilio/rest/flex_api/v1/call.py +++ b/examples/python/twilio/rest/flex_api/v1/call.py @@ -15,6 +15,7 @@ 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 @@ -72,6 +73,24 @@ async def update_async(self) -> "CallInstance": """ return await self._proxy.update_async() + def update_with_http_info(self) -> ApiResponse: + """ + Update the CallInstance 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 CallInstance 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 @@ -98,12 +117,12 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Voice/{sid}".format(**self._solution) - def update(self) -> CallInstance: + def _update(self) -> tuple: """ - Update the CallInstance - + Internal helper for update operation - :returns: The updated CallInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of({}) @@ -111,18 +130,37 @@ def update(self) -> CallInstance: 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) -> CallInstance: + """ + Update the CallInstance + + + :returns: The updated CallInstance + """ + payload, _, _ = self._update() return CallInstance(self._version, payload, sid=self._solution["sid"]) - async def update_async(self) -> CallInstance: + def update_with_http_info(self) -> ApiResponse: """ - Asynchronous coroutine to update the CallInstance + Update the CallInstance and return response metadata - :returns: The updated CallInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update() + instance = CallInstance(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({}) @@ -130,12 +168,31 @@ async def update_async(self) -> CallInstance: headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async(self) -> CallInstance: + """ + Asynchronous coroutine to update the CallInstance + + + :returns: The updated CallInstance + """ + payload, _, _ = await self._update_async() return CallInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the CallInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async() + instance = CallInstance(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/examples/python/twilio/rest/flex_api/v1/credential/aws/__init__.py b/examples/python/twilio/rest/flex_api/v1/credential/aws/__init__.py index 8c6ee892d..ffa795126 100644 --- a/examples/python/twilio/rest/flex_api/v1/credential/aws/__init__.py +++ b/examples/python/twilio/rest/flex_api/v1/credential/aws/__init__.py @@ -15,6 +15,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 @@ -82,6 +83,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 @@ -100,6 +119,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, test_string: Union[str, object] = values.unset, @@ -136,6 +173,42 @@ async def update_async( test_boolean=test_boolean, ) + def update_with_http_info( + self, + test_string: Union[str, object] = values.unset, + test_boolean: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the AwsInstance with HTTP info + + :param test_string: + :param test_boolean: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + test_string=test_string, + test_boolean=test_boolean, + ) + + async def update_with_http_info_async( + self, + test_string: Union[str, object] = values.unset, + test_boolean: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AwsInstance with HTTP info + + :param test_string: + :param test_boolean: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + test_string=test_string, + test_boolean=test_boolean, + ) + @property def history(self) -> HistoryList: """ @@ -239,18 +312,16 @@ async def fetch_async(self) -> AwsInstance: sid=self._solution["sid"], ) - def update( + def _update( self, test_string: Union[str, object] = values.unset, test_boolean: Union[bool, object] = values.unset, - ) -> AwsInstance: + ) -> tuple: """ - Update the AwsInstance + Internal helper for update operation - :param test_string: - :param test_boolean: - - :returns: The updated AwsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -265,25 +336,56 @@ def update( headers["Accept"] = "application/json" - payload = self._version.update( + return self._version.update_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return AwsInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( + def update( self, test_string: Union[str, object] = values.unset, test_boolean: Union[bool, object] = values.unset, ) -> AwsInstance: """ - Asynchronous coroutine to update the AwsInstance + Update the AwsInstance :param test_string: :param test_boolean: :returns: The updated AwsInstance """ + payload, _, _ = self._update(test_string=test_string, test_boolean=test_boolean) + return AwsInstance(self._version, payload, sid=self._solution["sid"]) + + def update_with_http_info( + self, + test_string: Union[str, object] = values.unset, + test_boolean: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Update the AwsInstance and return response metadata + + :param test_string: + :param test_boolean: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + test_string=test_string, test_boolean=test_boolean + ) + instance = AwsInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + test_string: Union[str, object] = values.unset, + test_boolean: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -297,12 +399,47 @@ async def update_async( headers["Accept"] = "application/json" - payload = await self._version.update_async( + return await self._version.update_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def update_async( + self, + test_string: Union[str, object] = values.unset, + test_boolean: Union[bool, object] = values.unset, + ) -> AwsInstance: + """ + Asynchronous coroutine to update the AwsInstance + + :param test_string: + :param test_boolean: + + :returns: The updated AwsInstance + """ + payload, _, _ = await self._update_async( + test_string=test_string, test_boolean=test_boolean + ) return AwsInstance(self._version, payload, sid=self._solution["sid"]) + async def update_with_http_info_async( + self, + test_string: Union[str, object] = values.unset, + test_boolean: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AwsInstance and return response metadata + + :param test_string: + :param test_boolean: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + test_string=test_string, test_boolean=test_boolean + ) + instance = AwsInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + @property def history(self) -> HistoryList: """ @@ -405,6 +542,56 @@ async def stream_async( return 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, @@ -458,6 +645,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, @@ -524,6 +761,78 @@ async def page_async( ) return AwsPage(self._version, response) + def page_with_http_info( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AwsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AwsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with AwsPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + ( + response, + status_code, + response_headers, + ) = await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AwsPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> AwsPage: """ Retrieve a specific page of AwsInstance records from the API. diff --git a/examples/python/twilio/rest/flex_api/v1/credential/aws/history.py b/examples/python/twilio/rest/flex_api/v1/credential/aws/history.py index dbf4a08a5..0ebd19997 100644 --- a/examples/python/twilio/rest/flex_api/v1/credential/aws/history.py +++ b/examples/python/twilio/rest/flex_api/v1/credential/aws/history.py @@ -15,6 +15,7 @@ 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 @@ -88,6 +89,34 @@ async def fetch_async( add_ons_data=add_ons_data, ) + def fetch_with_http_info( + self, add_ons_data: Union[Dict[str, object], object] = values.unset + ) -> ApiResponse: + """ + Fetch the HistoryInstance with HTTP info + + :param add_ons_data: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info( + add_ons_data=add_ons_data, + ) + + async def fetch_with_http_info_async( + self, add_ons_data: Union[Dict[str, object], object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the HistoryInstance with HTTP info + + :param add_ons_data: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async( + add_ons_data=add_ons_data, + ) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/examples/python/twilio/rest/flex_api/v1/credential/new_credentials.py b/examples/python/twilio/rest/flex_api/v1/credential/new_credentials.py index d4a02e023..72f7afe0e 100644 --- a/examples/python/twilio/rest/flex_api/v1/credential/new_credentials.py +++ b/examples/python/twilio/rest/flex_api/v1/credential/new_credentials.py @@ -16,6 +16,7 @@ from datetime import date, 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 @@ -70,7 +71,7 @@ def __init__(self, version: Version): self._uri = "/Credentials/AWS" - def create( + def _create( self, test_string: str, test_boolean: Union[bool, object] = values.unset, @@ -89,29 +90,12 @@ def create( test_any_array: Union[List[object], object] = values.unset, permissions: Union[List[str], object] = values.unset, some_a2p_thing: Union[str, object] = values.unset, - ) -> NewCredentialsInstance: + ) -> tuple: """ - Create the NewCredentialsInstance + Internal helper for create operation - :param test_string: - :param test_boolean: - :param test_integer: - :param test_number: - :param test_number_float: - :param test_number_double: - :param test_number_int32: - :param test_number_int64: - :param test_object: - :param test_date_time: - :param test_date: - :param test_enum: - :param test_object_array: - :param test_any_type: - :param test_any_array: - :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`. - :param some_a2p_thing: - - :returns: The created NewCredentialsInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -145,13 +129,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return NewCredentialsInstance(self._version, payload) - - async def create_async( + def create( self, test_string: str, test_boolean: Union[bool, object] = values.unset, @@ -172,7 +154,7 @@ async def create_async( some_a2p_thing: Union[str, object] = values.unset, ) -> NewCredentialsInstance: """ - Asynchronously create the NewCredentialsInstance + Create the NewCredentialsInstance :param test_string: :param test_boolean: @@ -194,6 +176,118 @@ async def create_async( :returns: The created NewCredentialsInstance """ + payload, _, _ = self._create( + test_string=test_string, + test_boolean=test_boolean, + test_integer=test_integer, + test_number=test_number, + test_number_float=test_number_float, + test_number_double=test_number_double, + test_number_int32=test_number_int32, + test_number_int64=test_number_int64, + test_object=test_object, + test_date_time=test_date_time, + test_date=test_date, + test_enum=test_enum, + test_object_array=test_object_array, + test_any_type=test_any_type, + test_any_array=test_any_array, + permissions=permissions, + some_a2p_thing=some_a2p_thing, + ) + return NewCredentialsInstance(self._version, payload) + + def create_with_http_info( + self, + test_string: str, + test_boolean: Union[bool, object] = values.unset, + test_integer: Union[int, object] = values.unset, + test_number: Union[float, object] = values.unset, + test_number_float: Union[float, object] = values.unset, + test_number_double: Union[float, object] = values.unset, + test_number_int32: Union[float, object] = values.unset, + test_number_int64: Union[int, object] = values.unset, + test_object: Union[Dict[str, object], object] = values.unset, + test_date_time: Union[datetime, object] = values.unset, + test_date: Union[date, object] = values.unset, + test_enum: Union["NewCredentialsInstance.Status", object] = values.unset, + test_object_array: Union[List[object], object] = values.unset, + test_any_type: Union[object, object] = values.unset, + test_any_array: Union[List[object], object] = values.unset, + permissions: Union[List[str], object] = values.unset, + some_a2p_thing: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Create the NewCredentialsInstance and return response metadata + + :param test_string: + :param test_boolean: + :param test_integer: + :param test_number: + :param test_number_float: + :param test_number_double: + :param test_number_int32: + :param test_number_int64: + :param test_object: + :param test_date_time: + :param test_date: + :param test_enum: + :param test_object_array: + :param test_any_type: + :param test_any_array: + :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`. + :param some_a2p_thing: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + test_string=test_string, + test_boolean=test_boolean, + test_integer=test_integer, + test_number=test_number, + test_number_float=test_number_float, + test_number_double=test_number_double, + test_number_int32=test_number_int32, + test_number_int64=test_number_int64, + test_object=test_object, + test_date_time=test_date_time, + test_date=test_date, + test_enum=test_enum, + test_object_array=test_object_array, + test_any_type=test_any_type, + test_any_array=test_any_array, + permissions=permissions, + some_a2p_thing=some_a2p_thing, + ) + instance = NewCredentialsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + test_string: str, + test_boolean: Union[bool, object] = values.unset, + test_integer: Union[int, object] = values.unset, + test_number: Union[float, object] = values.unset, + test_number_float: Union[float, object] = values.unset, + test_number_double: Union[float, object] = values.unset, + test_number_int32: Union[float, object] = values.unset, + test_number_int64: Union[int, object] = values.unset, + test_object: Union[Dict[str, object], object] = values.unset, + test_date_time: Union[datetime, object] = values.unset, + test_date: Union[date, object] = values.unset, + test_enum: Union["NewCredentialsInstance.Status", object] = values.unset, + test_object_array: Union[List[object], object] = values.unset, + test_any_type: Union[object, object] = values.unset, + test_any_array: Union[List[object], object] = values.unset, + permissions: Union[List[str], object] = values.unset, + some_a2p_thing: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { @@ -226,12 +320,139 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + test_string: str, + test_boolean: Union[bool, object] = values.unset, + test_integer: Union[int, object] = values.unset, + test_number: Union[float, object] = values.unset, + test_number_float: Union[float, object] = values.unset, + test_number_double: Union[float, object] = values.unset, + test_number_int32: Union[float, object] = values.unset, + test_number_int64: Union[int, object] = values.unset, + test_object: Union[Dict[str, object], object] = values.unset, + test_date_time: Union[datetime, object] = values.unset, + test_date: Union[date, object] = values.unset, + test_enum: Union["NewCredentialsInstance.Status", object] = values.unset, + test_object_array: Union[List[object], object] = values.unset, + test_any_type: Union[object, object] = values.unset, + test_any_array: Union[List[object], object] = values.unset, + permissions: Union[List[str], object] = values.unset, + some_a2p_thing: Union[str, object] = values.unset, + ) -> NewCredentialsInstance: + """ + Asynchronously create the NewCredentialsInstance + + :param test_string: + :param test_boolean: + :param test_integer: + :param test_number: + :param test_number_float: + :param test_number_double: + :param test_number_int32: + :param test_number_int64: + :param test_object: + :param test_date_time: + :param test_date: + :param test_enum: + :param test_object_array: + :param test_any_type: + :param test_any_array: + :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`. + :param some_a2p_thing: + + :returns: The created NewCredentialsInstance + """ + payload, _, _ = await self._create_async( + test_string=test_string, + test_boolean=test_boolean, + test_integer=test_integer, + test_number=test_number, + test_number_float=test_number_float, + test_number_double=test_number_double, + test_number_int32=test_number_int32, + test_number_int64=test_number_int64, + test_object=test_object, + test_date_time=test_date_time, + test_date=test_date, + test_enum=test_enum, + test_object_array=test_object_array, + test_any_type=test_any_type, + test_any_array=test_any_array, + permissions=permissions, + some_a2p_thing=some_a2p_thing, + ) return NewCredentialsInstance(self._version, payload) + async def create_with_http_info_async( + self, + test_string: str, + test_boolean: Union[bool, object] = values.unset, + test_integer: Union[int, object] = values.unset, + test_number: Union[float, object] = values.unset, + test_number_float: Union[float, object] = values.unset, + test_number_double: Union[float, object] = values.unset, + test_number_int32: Union[float, object] = values.unset, + test_number_int64: Union[int, object] = values.unset, + test_object: Union[Dict[str, object], object] = values.unset, + test_date_time: Union[datetime, object] = values.unset, + test_date: Union[date, object] = values.unset, + test_enum: Union["NewCredentialsInstance.Status", object] = values.unset, + test_object_array: Union[List[object], object] = values.unset, + test_any_type: Union[object, object] = values.unset, + test_any_array: Union[List[object], object] = values.unset, + permissions: Union[List[str], object] = values.unset, + some_a2p_thing: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the NewCredentialsInstance and return response metadata + + :param test_string: + :param test_boolean: + :param test_integer: + :param test_number: + :param test_number_float: + :param test_number_double: + :param test_number_int32: + :param test_number_int64: + :param test_object: + :param test_date_time: + :param test_date: + :param test_enum: + :param test_object_array: + :param test_any_type: + :param test_any_array: + :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`. + :param some_a2p_thing: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + test_string=test_string, + test_boolean=test_boolean, + test_integer=test_integer, + test_number=test_number, + test_number_float=test_number_float, + test_number_double=test_number_double, + test_number_int32=test_number_int32, + test_number_int64=test_number_int64, + test_object=test_object, + test_date_time=test_date_time, + test_date=test_date, + test_enum=test_enum, + test_object_array=test_object_array, + test_any_type=test_any_type, + test_any_array=test_any_array, + permissions=permissions, + some_a2p_thing=some_a2p_thing, + ) + instance = NewCredentialsInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def __repr__(self) -> str: """ Provide a friendly representation diff --git a/examples/python/twilio/rest/oauth/v2/token.py b/examples/python/twilio/rest/oauth/v2/token.py index 860423db6..ce5b8b325 100644 --- a/examples/python/twilio/rest/oauth/v2/token.py +++ b/examples/python/twilio/rest/oauth/v2/token.py @@ -15,6 +15,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 @@ -62,7 +63,7 @@ def __init__(self, version: Version): self._uri = "/token" - def create( + def _create( self, grant_type: Union[str, object] = values.unset, client_id: Union[str, object] = values.unset, @@ -72,20 +73,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( @@ -106,13 +99,11 @@ def create( headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) - return TokenInstance(self._version, payload) - - async def create_async( + def create( self, grant_type: Union[str, object] = values.unset, client_id: Union[str, object] = values.unset, @@ -124,7 +115,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. @@ -137,6 +128,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: 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 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: 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( { @@ -156,12 +214,85 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, + grant_type: 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 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: 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 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/examples/python/twilio/rest/versionless/deployed_devices/fleet.py b/examples/python/twilio/rest/versionless/deployed_devices/fleet.py index 89ef036e2..80d0ff025 100644 --- a/examples/python/twilio/rest/versionless/deployed_devices/fleet.py +++ b/examples/python/twilio/rest/versionless/deployed_devices/fleet.py @@ -15,6 +15,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 @@ -90,6 +91,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 __repr__(self) -> str: """ Provide a friendly representation @@ -180,13 +199,12 @@ def __init__(self, version: Version): self._uri = "/Fleets" - def create(self, name: Union[str, object] = values.unset) -> FleetInstance: + def _create(self, name: Union[str, object] = values.unset) -> tuple: """ - Create the FleetInstance + Internal helper for create operation - :param name: - - :returns: The created FleetInstance + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -200,21 +218,41 @@ def create(self, name: Union[str, object] = values.unset) -> FleetInstance: headers["Accept"] = "application/json" - payload = self._version.create( + return self._version.create_with_response_info( method="POST", uri=self._uri, data=data, headers=headers ) + def create(self, name: Union[str, object] = values.unset) -> FleetInstance: + """ + Create the FleetInstance + + :param name: + + :returns: The created FleetInstance + """ + payload, _, _ = self._create(name=name) return FleetInstance(self._version, payload) - async def create_async( + def create_with_http_info( self, name: Union[str, object] = values.unset - ) -> FleetInstance: + ) -> ApiResponse: """ - Asynchronously create the FleetInstance + Create the FleetInstance and return response metadata :param name: - :returns: The created FleetInstance + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create(name=name) + instance = FleetInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self, name: Union[str, object] = values.unset) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ data = values.of( @@ -228,12 +266,37 @@ async def create_async( headers["Accept"] = "application/json" - payload = await self._version.create_async( + return await self._version.create_with_response_info_async( method="POST", uri=self._uri, data=data, headers=headers ) + async def create_async( + self, name: Union[str, object] = values.unset + ) -> FleetInstance: + """ + Asynchronously create the FleetInstance + + :param name: + + :returns: The created FleetInstance + """ + payload, _, _ = await self._create_async(name=name) return FleetInstance(self._version, payload) + async def create_with_http_info_async( + self, name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the FleetInstance and return response metadata + + :param name: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async(name=name) + instance = FleetInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def get(self, sid: str) -> FleetContext: """ Constructs a FleetContext diff --git a/examples/python/twilio/rest/versionless/understand/assistant.py b/examples/python/twilio/rest/versionless/understand/assistant.py index 18b4b06a2..00d4f7a75 100644 --- a/examples/python/twilio/rest/versionless/understand/assistant.py +++ b/examples/python/twilio/rest/versionless/understand/assistant.py @@ -15,6 +15,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 @@ -125,6 +126,56 @@ async def stream_async( return 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, @@ -178,6 +229,56 @@ async def list_async( ) ] + 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, @@ -244,6 +345,78 @@ async def page_async( ) 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. diff --git a/examples/ruby/lib/twilio-ruby/rest/api/v2010/account.rb b/examples/ruby/lib/twilio-ruby/rest/api/v2010/account.rb index cf2b68dcf..020c943d7 100644 --- a/examples/ruby/lib/twilio-ruby/rest/api/v2010/account.rb +++ b/examples/ruby/lib/twilio-ruby/rest/api/v2010/account.rb @@ -23,6 +23,7 @@ class AccountList < ListResource # @return [AccountList] AccountList def initialize(version) super(version) + # Path Solution @solution = {} @uri = "/Accounts.json" @@ -59,6 +60,43 @@ def create( ) end + ## + # Create the AccountInstanceMetadata + # @param [String] recording_status_callback + # @param [Array[String]] recording_status_callback_event + # @param [String] twiml + # @param [AccountEnumXTwilioWebhookEnabled] x_twilio_webhook_enabled + # @return [AccountInstance] Created AccountInstance + def create_with_metadata( + recording_status_callback: :unset, + recording_status_callback_event: :unset, + twiml: :unset, + x_twilio_webhook_enabled: :unset + ) + data = Twilio::Values.of({ + 'RecordingStatusCallback' => recording_status_callback, + 'RecordingStatusCallbackEvent' => Twilio.serialize_list(recording_status_callback_event) { |e| + e + }, + 'Twiml' => twiml, + }) + + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', + 'X-Twilio-Webhook-Enabled' => x_twilio_webhook_enabled, }) + + response = @version.create_with_metadata('POST', @uri, data: data, headers: headers) + account_instance = AccountInstance.new( + @version, + response.body, + ) + AccountInstanceMetadata.new( + @version, + account_instance, + response.headers, + response.status_code + ) + end + ## # Lists AccountInstance records from the API as a list. # Unlike stream(), this operation is eager and will load `limit` records into @@ -116,6 +154,37 @@ def stream(date_created: :unset, date_test: :unset, date_created_before: :unset, @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]) end + ## + # Lists AccountPageMetadata records from the API as a list. + # @param [Time] date_created + # @param [Date] date_test + # @param [Time] date_created_before + # @param [Time] date_created_after + # @param [Integer] limit Upper limit for the number of records to return. stream() + # guarantees to never return more than limit. Default is no limit + # @param [Integer] page_size Number of records to fetch per request, when + # not set will use the default value of 50 records. If no page_size is defined + # but a limit is defined, stream() will attempt to read the limit with the most + # efficient page size, i.e. min(limit, 1000) + # @return [Array] Array of up to limit results + def list_with_metadata(date_created: :unset, date_test: :unset, date_created_before: :unset, + date_created_after: :unset, limit: nil, page_size: nil) + limits = @version.read_limits(limit, page_size) + params = Twilio::Values.of({ + 'DateCreated' => Twilio.serialize_iso8601_datetime(date_created), + 'Date.Test' => Twilio.serialize_iso8601_date(date_test), + 'DateCreated<' => Twilio.serialize_iso8601_datetime(date_created_before), + 'DateCreated>' => Twilio.serialize_iso8601_datetime(date_created_after), + + 'PageSize' => page_size, + }); + headers = Twilio::Values.of({}) + + response = @version.page('GET', @uri, params: params, headers: headers) + + AccountPageMetadata.new(@version, response, @solution, limits[:limit]) + end + ## # When passed a block, yields AccountInstance records from the API. # This operation lazily loads records as efficiently as possible until the limit @@ -204,6 +273,23 @@ def delete @version.delete('DELETE', @uri, headers: headers) end + ## + # Delete the AccountInstanceMetadata + # @return [Boolean] True if delete succeeds, false otherwise + def delete_with_metadata + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.delete_with_metadata('DELETE', @uri, headers: headers) + account_instance = AccountInstance.new( + @version, + response.body, + account_sid: @solution[:account_sid], + sid: @solution[:sid], + ) + AccountInstanceMetadata.new(@version, account_instance, response.headers, + response.status_code) + end + ## # Fetch the AccountInstance # @return [AccountInstance] Fetched AccountInstance @@ -218,6 +304,26 @@ def fetch ) end + ## + # Fetch the AccountInstanceMetadata + # @return [AccountInstance] Fetched AccountInstance + def fetch_with_metadata + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.fetch_with_metadata('GET', @uri, headers: headers) + account_instance = AccountInstance.new( + @version, + response.body, + sid: @solution[:sid], + ) + AccountInstanceMetadata.new( + @version, + account_instance, + response.headers, + response.status_code + ) + end + ## # Update the AccountInstance # @param [String] pause_behavior @@ -242,6 +348,36 @@ def update( ) end + ## + # Update the AccountInstanceMetadata + # @param [String] pause_behavior + # @param [Status] status + # @return [AccountInstance] Updated AccountInstance + def update_with_metadata( + pause_behavior: :unset, + status: nil + ) + data = Twilio::Values.of({ + 'Status' => status, + 'PauseBehavior' => pause_behavior, + }) + + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.update_with_metadata('POST', @uri, data: data, headers: headers) + account_instance = AccountInstance.new( + @version, + response.body, + sid: @solution[:sid], + ) + AccountInstanceMetadata.new( + @version, + account_instance, + response.headers, + response.status_code + ) + end + ## # Access the calls # @return [CallList] @@ -277,6 +413,53 @@ def inspect end end + class AccountInstanceMetadata < InstanceResourceMetadata + ## + # Initializes a new AccountInstanceMetadata. + # @param [Version] version Version that contains the resource + # @param [}AccountInstance] account_instance The instance associated with the metadata. + # @param [Hash] headers Header object with response headers. + # @param [Integer] status_code The HTTP status code of the response. + # @return [AccountInstanceMetadata] The initialized instance with metadata. + def initialize(version, account_instance, headers, status_code) + super(version, headers, status_code) + @account_instance = account_instance + end + + def account + @account_instance + end + + def headers + @headers + end + + def status_code + @status_code + end + + def to_s + "" + end + end + + class AccountListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @account_instance = payload.body[key].map do |data| + AccountInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def account_instance + @instance + end + end + class AccountPage < Page ## # Initialize the AccountPage @@ -306,6 +489,62 @@ def to_s end end + class AccountPageMetadata < PageMetadata + attr_reader :account_page + + def initialize(version, response, solution, limit) + super(version, response) + @account_page = [] + @limit = limit + key = get_key(response.body) + number_of_records = response.body[key].size + while (limit != :unset && number_of_records <= limit) + @account_page << AccountListResponse.new(version, @payload, key) + @payload = self.next_page + break unless @payload + + number_of_records += @payload.body[key].size + end + # Path Solution + @solution = solution + end + + def each + @account_page.each do |record| + yield record + end + end + + def to_s + ''; + end + end + + class AccountListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @account = payload.body[key].map do |data| + AccountInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def account + @account + end + + def headers + @headers + end + + def status_code + @status_code + end + end + class AccountInstance < InstanceResource ## # Initialize the AccountInstance diff --git a/examples/ruby/lib/twilio-ruby/rest/api/v2010/account/call.rb b/examples/ruby/lib/twilio-ruby/rest/api/v2010/account/call.rb index f30efc324..9ae54228d 100644 --- a/examples/ruby/lib/twilio-ruby/rest/api/v2010/account/call.rb +++ b/examples/ruby/lib/twilio-ruby/rest/api/v2010/account/call.rb @@ -24,6 +24,7 @@ class CallList < ListResource # @return [CallList] CallList def initialize(version, account_sid: nil) super(version) + # Path Solution @solution = { account_sid: account_sid } @uri = "/Accounts/#{@solution[:account_sid]}/Calls.json" @@ -63,6 +64,44 @@ def create( ) end + ## + # Create the CallInstanceMetadata + # @param [String] required_string_property + # @param [Array[String]] test_array_of_strings + # @param [Array[String]] test_array_of_uri + # @param [String] test_method The HTTP method that we should use to request the `TestArrayOfUri`. + # @return [CallInstance] Created CallInstance + def create_with_metadata( + required_string_property: nil, + test_array_of_strings: :unset, + test_array_of_uri: :unset, + test_method: nil + ) + data = Twilio::Values.of({ + 'RequiredStringProperty' => required_string_property, + 'TestMethod' => test_method, + 'TestArrayOfStrings' => Twilio.serialize_list(test_array_of_strings) { |e| + e + }, + 'TestArrayOfUri' => Twilio.serialize_list(test_array_of_uri) { |e| e }, + }) + + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.create_with_metadata('POST', @uri, data: data, headers: headers) + call_instance = CallInstance.new( + @version, + response.body, + account_sid: @solution[:account_sid], + ) + CallInstanceMetadata.new( + @version, + call_instance, + response.headers, + response.status_code + ) + end + ## # Access the feedback_call_summary # @return [FeedbackCallSummaryList] @@ -105,6 +144,22 @@ def delete @version.delete('DELETE', @uri, headers: headers) end + ## + # Delete the CallInstanceMetadata + # @return [Boolean] True if delete succeeds, false otherwise + def delete_with_metadata + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.delete_with_metadata('DELETE', @uri, headers: headers) + call_instance = CallInstance.new( + @version, + response.body, + account_sid: @solution[:account_sid], + sid: @solution[:sid], + ) + CallInstanceMetadata.new(@version, call_instance, response.headers, response.status_code) + end + ## # Fetch the CallInstance # @return [CallInstance] Fetched CallInstance @@ -120,6 +175,27 @@ def fetch ) end + ## + # Fetch the CallInstanceMetadata + # @return [CallInstance] Fetched CallInstance + def fetch_with_metadata + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.fetch_with_metadata('GET', @uri, headers: headers) + call_instance = CallInstance.new( + @version, + response.body, + account_sid: @solution[:account_sid], + test_integer: @solution[:test_integer], + ) + CallInstanceMetadata.new( + @version, + call_instance, + response.headers, + response.status_code + ) + end + ## # Access the feedback_call_summary # @return [FeedbackCallSummaryList] @@ -156,6 +232,53 @@ def inspect end end + class CallInstanceMetadata < InstanceResourceMetadata + ## + # Initializes a new CallInstanceMetadata. + # @param [Version] version Version that contains the resource + # @param [}CallInstance] call_instance The instance associated with the metadata. + # @param [Hash] headers Header object with response headers. + # @param [Integer] status_code The HTTP status code of the response. + # @return [CallInstanceMetadata] The initialized instance with metadata. + def initialize(version, call_instance, headers, status_code) + super(version, headers, status_code) + @call_instance = call_instance + end + + def call + @call_instance + end + + def headers + @headers + end + + def status_code + @status_code + end + + def to_s + "" + end + end + + class CallListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @call_instance = payload.body[key].map do |data| + CallInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def call_instance + @instance + end + end + class CallPage < Page ## # Initialize the CallPage @@ -185,6 +308,62 @@ def to_s end end + class CallPageMetadata < PageMetadata + attr_reader :call_page + + def initialize(version, response, solution, limit) + super(version, response) + @call_page = [] + @limit = limit + key = get_key(response.body) + number_of_records = response.body[key].size + while (limit != :unset && number_of_records <= limit) + @call_page << CallListResponse.new(version, @payload, key) + @payload = self.next_page + break unless @payload + + number_of_records += @payload.body[key].size + end + # Path Solution + @solution = solution + end + + def each + @call_page.each do |record| + yield record + end + end + + def to_s + ''; + end + end + + class CallListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @call = payload.body[key].map do |data| + CallInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def call + @call + end + + def headers + @headers + end + + def status_code + @status_code + end + end + class CallInstance < InstanceResource ## # Initialize the CallInstance diff --git a/examples/ruby/lib/twilio-ruby/rest/api/v2010/account/call/feedback_call_summary.rb b/examples/ruby/lib/twilio-ruby/rest/api/v2010/account/call/feedback_call_summary.rb index b3f06d8e6..e2e4ed969 100644 --- a/examples/ruby/lib/twilio-ruby/rest/api/v2010/account/call/feedback_call_summary.rb +++ b/examples/ruby/lib/twilio-ruby/rest/api/v2010/account/call/feedback_call_summary.rb @@ -25,6 +25,7 @@ class FeedbackCallSummaryList < ListResource # @return [FeedbackCallSummaryList] FeedbackCallSummaryList def initialize(version, account_sid: nil) super(version) + # Path Solution @solution = { account_sid: account_sid } end @@ -78,6 +79,40 @@ def update( ) end + ## + # Update the FeedbackCallSummaryInstanceMetadata + # @param [String] account_sid + # @param [Date] end_date + # @param [Date] start_date + # @return [FeedbackCallSummaryInstance] Updated FeedbackCallSummaryInstance + def update_with_metadata( + account_sid: :unset, + end_date: nil, + start_date: nil + ) + data = Twilio::Values.of({ + 'EndDate' => Twilio.serialize_iso8601_date(end_date), + 'StartDate' => Twilio.serialize_iso8601_date(start_date), + 'AccountSid' => account_sid, + }) + + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.update_with_metadata('POST', @uri, data: data, headers: headers) + feedbackCallSummary_instance = FeedbackCallSummaryInstance.new( + @version, + response.body, + account_sid: @solution[:account_sid], + sid: @solution[:sid], + ) + FeedbackCallSummaryInstanceMetadata.new( + @version, + feedbackCallSummary_instance, + response.headers, + response.status_code + ) + end + ## # Provide a user friendly representation def to_s @@ -93,6 +128,53 @@ def inspect end end + class FeedbackCallSummaryInstanceMetadata < InstanceResourceMetadata + ## + # Initializes a new FeedbackCallSummaryInstanceMetadata. + # @param [Version] version Version that contains the resource + # @param [}FeedbackCallSummaryInstance] feedback_call_summary_instance The instance associated with the metadata. + # @param [Hash] headers Header object with response headers. + # @param [Integer] status_code The HTTP status code of the response. + # @return [FeedbackCallSummaryInstanceMetadata] The initialized instance with metadata. + def initialize(version, feedback_call_summary_instance, headers, status_code) + super(version, headers, status_code) + @feedback_call_summary_instance = feedback_call_summary_instance + end + + def feedback_call_summary + @feedback_call_summary_instance + end + + def headers + @headers + end + + def status_code + @status_code + end + + def to_s + "" + end + end + + class FeedbackCallSummaryListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @feedback_call_summary_instance = payload.body[key].map do |data| + FeedbackCallSummaryInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def feedback_call_summary_instance + @instance + end + end + class FeedbackCallSummaryPage < Page ## # Initialize the FeedbackCallSummaryPage @@ -122,6 +204,63 @@ def to_s end end + class FeedbackCallSummaryPageMetadata < PageMetadata + attr_reader :feedback_call_summary_page + + def initialize(version, response, solution, limit) + super(version, response) + @feedback_call_summary_page = [] + @limit = limit + key = get_key(response.body) + number_of_records = response.body[key].size + while (limit != :unset && number_of_records <= limit) + @feedback_call_summary_page << FeedbackCallSummaryListResponse.new(version, @payload, + key) + @payload = self.next_page + break unless @payload + + number_of_records += @payload.body[key].size + end + # Path Solution + @solution = solution + end + + def each + @feedback_call_summary_page.each do |record| + yield record + end + end + + def to_s + ''; + end + end + + class FeedbackCallSummaryListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @feedback_call_summary = payload.body[key].map do |data| + FeedbackCallSummaryInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def feedback_call_summary + @feedback_call_summary + end + + def headers + @headers + end + + def status_code + @status_code + end + end + class FeedbackCallSummaryInstance < InstanceResource ## # Initialize the FeedbackCallSummaryInstance diff --git a/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/call.rb b/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/call.rb index 92997381b..9ab74c727 100644 --- a/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/call.rb +++ b/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/call.rb @@ -23,6 +23,7 @@ class CallList < ListResource # @return [CallList] CallList def initialize(version) super(version) + # Path Solution @solution = {} end @@ -61,6 +62,26 @@ def update ) end + ## + # Update the CallInstanceMetadata + # @return [CallInstance] Updated CallInstance + def update_with_metadata + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.update_with_metadata('POST', @uri, headers: headers) + call_instance = CallInstance.new( + @version, + response.body, + sid: @solution[:sid], + ) + CallInstanceMetadata.new( + @version, + call_instance, + response.headers, + response.status_code + ) + end + ## # Provide a user friendly representation def to_s @@ -76,6 +97,53 @@ def inspect end end + class CallInstanceMetadata < InstanceResourceMetadata + ## + # Initializes a new CallInstanceMetadata. + # @param [Version] version Version that contains the resource + # @param [}CallInstance] call_instance The instance associated with the metadata. + # @param [Hash] headers Header object with response headers. + # @param [Integer] status_code The HTTP status code of the response. + # @return [CallInstanceMetadata] The initialized instance with metadata. + def initialize(version, call_instance, headers, status_code) + super(version, headers, status_code) + @call_instance = call_instance + end + + def call + @call_instance + end + + def headers + @headers + end + + def status_code + @status_code + end + + def to_s + "" + end + end + + class CallListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @call_instance = payload.body[key].map do |data| + CallInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def call_instance + @instance + end + end + class CallPage < Page ## # Initialize the CallPage @@ -105,6 +173,62 @@ def to_s end end + class CallPageMetadata < PageMetadata + attr_reader :call_page + + def initialize(version, response, solution, limit) + super(version, response) + @call_page = [] + @limit = limit + key = get_key(response.body) + number_of_records = response.body[key].size + while (limit != :unset && number_of_records <= limit) + @call_page << CallListResponse.new(version, @payload, key) + @payload = self.next_page + break unless @payload + + number_of_records += @payload.body[key].size + end + # Path Solution + @solution = solution + end + + def each + @call_page.each do |record| + yield record + end + end + + def to_s + ''; + end + end + + class CallListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @call = payload.body[key].map do |data| + CallInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def call + @call + end + + def headers + @headers + end + + def status_code + @status_code + end + end + class CallInstance < InstanceResource ## # Initialize the CallInstance diff --git a/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential.rb b/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential.rb index be8d63b4e..3984a819a 100644 --- a/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential.rb +++ b/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential.rb @@ -23,6 +23,7 @@ class CredentialList < ListResource # @return [CredentialList] CredentialList def initialize(version) super(version) + # Path Solution @solution = {} @uri = "/Credentials" @@ -88,6 +89,62 @@ def to_s end end + class CredentialPageMetadata < PageMetadata + attr_reader :credential_page + + def initialize(version, response, solution, limit) + super(version, response) + @credential_page = [] + @limit = limit + key = get_key(response.body) + number_of_records = response.body[key].size + while (limit != :unset && number_of_records <= limit) + @credential_page << CredentialListResponse.new(version, @payload, key) + @payload = self.next_page + break unless @payload + + number_of_records += @payload.body[key].size + end + # Path Solution + @solution = solution + end + + def each + @credential_page.each do |record| + yield record + end + end + + def to_s + ''; + end + end + + class CredentialListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @credential = payload.body[key].map do |data| + CredentialInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def credential + @credential + end + + def headers + @headers + end + + def status_code + @status_code + end + end + class CredentialInstance < InstanceResource ## # Initialize the CredentialInstance diff --git a/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential/aws.rb b/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential/aws.rb index b281daad5..4e94beb54 100644 --- a/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential/aws.rb +++ b/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential/aws.rb @@ -24,6 +24,7 @@ class AwsList < ListResource # @return [AwsList] AwsList def initialize(version) super(version) + # Path Solution @solution = {} @uri = "/Credentials/AWS" @@ -68,6 +69,28 @@ def stream(limit: nil, page_size: nil) @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]) end + ## + # Lists AwsPageMetadata records from the API as a list. + # @param [Integer] limit Upper limit for the number of records to return. stream() + # guarantees to never return more than limit. Default is no limit + # @param [Integer] page_size Number of records to fetch per request, when + # not set will use the default value of 50 records. If no page_size is defined + # but a limit is defined, stream() will attempt to read the limit with the most + # efficient page size, i.e. min(limit, 1000) + # @return [Array] Array of up to limit results + def list_with_metadata(limit: nil, page_size: nil) + limits = @version.read_limits(limit, page_size) + params = Twilio::Values.of({ + + 'PageSize' => page_size, + }); + headers = Twilio::Values.of({}) + + response = @version.page('GET', @uri, params: params, headers: headers) + + AwsPageMetadata.new(@version, response, @solution, limits[:limit]) + end + ## # When passed a block, yields AwsInstance records from the API. # This operation lazily loads records as efficiently as possible until the limit @@ -147,6 +170,22 @@ def delete @version.delete('DELETE', @uri, headers: headers) end + ## + # Delete the AwsInstanceMetadata + # @return [Boolean] True if delete succeeds, false otherwise + def delete_with_metadata + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.delete_with_metadata('DELETE', @uri, headers: headers) + aws_instance = AwsInstance.new( + @version, + response.body, + account_sid: @solution[:account_sid], + sid: @solution[:sid], + ) + AwsInstanceMetadata.new(@version, aws_instance, response.headers, response.status_code) + end + ## # Fetch the AwsInstance # @return [AwsInstance] Fetched AwsInstance @@ -161,6 +200,26 @@ def fetch ) end + ## + # Fetch the AwsInstanceMetadata + # @return [AwsInstance] Fetched AwsInstance + def fetch_with_metadata + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.fetch_with_metadata('GET', @uri, headers: headers) + aws_instance = AwsInstance.new( + @version, + response.body, + sid: @solution[:sid], + ) + AwsInstanceMetadata.new( + @version, + aws_instance, + response.headers, + response.status_code + ) + end + ## # Update the AwsInstance # @param [String] test_string @@ -185,6 +244,36 @@ def update( ) end + ## + # Update the AwsInstanceMetadata + # @param [String] test_string + # @param [Boolean] test_boolean + # @return [AwsInstance] Updated AwsInstance + def update_with_metadata( + test_string: :unset, + test_boolean: :unset + ) + data = Twilio::Values.of({ + 'TestString' => test_string, + 'TestBoolean' => test_boolean, + }) + + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.update_with_metadata('POST', @uri, data: data, headers: headers) + aws_instance = AwsInstance.new( + @version, + response.body, + sid: @solution[:sid], + ) + AwsInstanceMetadata.new( + @version, + aws_instance, + response.headers, + response.status_code + ) + end + ## # Access the history # @return [HistoryList] @@ -211,6 +300,53 @@ def inspect end end + class AwsInstanceMetadata < InstanceResourceMetadata + ## + # Initializes a new AwsInstanceMetadata. + # @param [Version] version Version that contains the resource + # @param [}AwsInstance] aws_instance The instance associated with the metadata. + # @param [Hash] headers Header object with response headers. + # @param [Integer] status_code The HTTP status code of the response. + # @return [AwsInstanceMetadata] The initialized instance with metadata. + def initialize(version, aws_instance, headers, status_code) + super(version, headers, status_code) + @aws_instance = aws_instance + end + + def aws + @aws_instance + end + + def headers + @headers + end + + def status_code + @status_code + end + + def to_s + "" + end + end + + class AwsListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @aws_instance = payload.body[key].map do |data| + AwsInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def aws_instance + @instance + end + end + class AwsPage < Page ## # Initialize the AwsPage @@ -240,6 +376,62 @@ def to_s end end + class AwsPageMetadata < PageMetadata + attr_reader :aws_page + + def initialize(version, response, solution, limit) + super(version, response) + @aws_page = [] + @limit = limit + key = get_key(response.body) + number_of_records = response.body[key].size + while (limit != :unset && number_of_records <= limit) + @aws_page << AwsListResponse.new(version, @payload, key) + @payload = self.next_page + break unless @payload + + number_of_records += @payload.body[key].size + end + # Path Solution + @solution = solution + end + + def each + @aws_page.each do |record| + yield record + end + end + + def to_s + ''; + end + end + + class AwsListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @aws = payload.body[key].map do |data| + AwsInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def aws + @aws + end + + def headers + @headers + end + + def status_code + @status_code + end + end + class AwsInstance < InstanceResource ## # Initialize the AwsInstance diff --git a/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential/aws/history.rb b/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential/aws/history.rb index b09d89364..2c38d55ef 100644 --- a/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential/aws/history.rb +++ b/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential/aws/history.rb @@ -25,6 +25,7 @@ class HistoryList < ListResource # @return [HistoryList] HistoryList def initialize(version, sid: nil) super(version) + # Path Solution @solution = { sid: sid } end @@ -68,6 +69,31 @@ def fetch( ) end + ## + # Fetch the HistoryInstanceMetadata + # @param [Hash] add_ons_data + # @return [HistoryInstance] Fetched HistoryInstance + def fetch_with_metadata( + add_ons_data: :unset + ) + params = Twilio::Values.of({}) + params.merge!(Twilio.prefixed_collapsible_map(add_ons_data, 'AddOns')) + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.fetch_with_metadata('GET', @uri, params: params, headers: headers) + history_instance = HistoryInstance.new( + @version, + response.body, + sid: @solution[:sid], + ) + HistoryInstanceMetadata.new( + @version, + history_instance, + response.headers, + response.status_code + ) + end + ## # Provide a user friendly representation def to_s @@ -83,6 +109,53 @@ def inspect end end + class HistoryInstanceMetadata < InstanceResourceMetadata + ## + # Initializes a new HistoryInstanceMetadata. + # @param [Version] version Version that contains the resource + # @param [}HistoryInstance] history_instance The instance associated with the metadata. + # @param [Hash] headers Header object with response headers. + # @param [Integer] status_code The HTTP status code of the response. + # @return [HistoryInstanceMetadata] The initialized instance with metadata. + def initialize(version, history_instance, headers, status_code) + super(version, headers, status_code) + @history_instance = history_instance + end + + def history + @history_instance + end + + def headers + @headers + end + + def status_code + @status_code + end + + def to_s + "" + end + end + + class HistoryListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @history_instance = payload.body[key].map do |data| + HistoryInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def history_instance + @instance + end + end + class HistoryPage < Page ## # Initialize the HistoryPage @@ -112,6 +185,62 @@ def to_s end end + class HistoryPageMetadata < PageMetadata + attr_reader :history_page + + def initialize(version, response, solution, limit) + super(version, response) + @history_page = [] + @limit = limit + key = get_key(response.body) + number_of_records = response.body[key].size + while (limit != :unset && number_of_records <= limit) + @history_page << HistoryListResponse.new(version, @payload, key) + @payload = self.next_page + break unless @payload + + number_of_records += @payload.body[key].size + end + # Path Solution + @solution = solution + end + + def each + @history_page.each do |record| + yield record + end + end + + def to_s + ''; + end + end + + class HistoryListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @history = payload.body[key].map do |data| + HistoryInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def history + @history + end + + def headers + @headers + end + + def status_code + @status_code + end + end + class HistoryInstance < InstanceResource ## # Initialize the HistoryInstance diff --git a/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential/new_credentials.rb b/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential/new_credentials.rb index 9508cd616..9df5fb50d 100644 --- a/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential/new_credentials.rb +++ b/examples/ruby/lib/twilio-ruby/rest/flex_api/v1/credential/new_credentials.rb @@ -24,6 +24,7 @@ class NewCredentialsList < ListResource # @return [NewCredentialsList] NewCredentialsList def initialize(version) super(version) + # Path Solution @solution = {} @uri = "/Credentials/AWS" @@ -101,6 +102,84 @@ def create( ) end + ## + # Create the NewCredentialsInstanceMetadata + # @param [String] test_string + # @param [Boolean] test_boolean + # @param [String] test_integer + # @param [Float] test_number + # @param [Float] test_number_float + # @param [Float] test_number_double + # @param [Float] test_number_int32 + # @param [String] test_number_int64 + # @param [Hash] test_object + # @param [Time] test_date_time + # @param [Date] test_date + # @param [Status] test_enum + # @param [Array[Hash]] test_object_array + # @param [Object] test_any_type + # @param [Array[Hash]] test_any_array + # @param [Array[String]] permissions A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + # @param [String] some_a2p_thing + # @return [NewCredentialsInstance] Created NewCredentialsInstance + def create_with_metadata( + test_string: nil, + test_boolean: :unset, + test_integer: :unset, + test_number: :unset, + test_number_float: :unset, + test_number_double: :unset, + test_number_int32: :unset, + test_number_int64: :unset, + test_object: :unset, + test_date_time: :unset, + test_date: :unset, + test_enum: :unset, + test_object_array: :unset, + test_any_type: :unset, + test_any_array: :unset, + permissions: :unset, + some_a2p_thing: :unset + ) + data = Twilio::Values.of({ + 'TestString' => test_string, + 'TestBoolean' => test_boolean, + 'TestInteger' => test_integer, + 'TestNumber' => test_number, + 'TestNumberFloat' => test_number_float, + 'TestNumberDouble' => test_number_double, + 'TestNumberInt32' => test_number_int32, + 'TestNumberInt64' => test_number_int64, + 'TestObject' => Twilio.serialize_object(test_object), + 'TestDateTime' => Twilio.serialize_iso8601_datetime(test_date_time), + 'TestDate' => Twilio.serialize_iso8601_date(test_date), + 'TestEnum' => test_enum, + 'TestObjectArray' => Twilio.serialize_list(test_object_array) { |e| + Twilio.serialize_object(e) + }, + 'TestAnyType' => Twilio.serialize_object(test_any_type), + 'TestAnyArray' => Twilio.serialize_list(test_any_array) { |e| + Twilio.serialize_object(e) + }, + 'Permissions' => Twilio.serialize_list(permissions) { |e| e }, + 'SomeA2PThing' => some_a2p_thing, + }) + + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.create_with_metadata('POST', @uri, data: data, headers: headers) + newCredentials_instance = NewCredentialsInstance.new( + @version, + response.body, + ) + NewCredentialsInstanceMetadata.new( + @version, + newCredentials_instance, + response.headers, + response.status_code + ) + end + # Provide a user friendly representation def to_s '#' @@ -136,6 +215,62 @@ def to_s end end + class NewCredentialsPageMetadata < PageMetadata + attr_reader :new_credentials_page + + def initialize(version, response, solution, limit) + super(version, response) + @new_credentials_page = [] + @limit = limit + key = get_key(response.body) + number_of_records = response.body[key].size + while (limit != :unset && number_of_records <= limit) + @new_credentials_page << NewCredentialsListResponse.new(version, @payload, key) + @payload = self.next_page + break unless @payload + + number_of_records += @payload.body[key].size + end + # Path Solution + @solution = solution + end + + def each + @new_credentials_page.each do |record| + yield record + end + end + + def to_s + ''; + end + end + + class NewCredentialsListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @new_credentials = payload.body[key].map do |data| + NewCredentialsInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def new_credentials + @new_credentials + end + + def headers + @headers + end + + def status_code + @status_code + end + end + class NewCredentialsInstance < InstanceResource ## # Initialize the NewCredentialsInstance diff --git a/examples/ruby/lib/twilio-ruby/rest/oauth/v2/token.rb b/examples/ruby/lib/twilio-ruby/rest/oauth/v2/token.rb index f2f54bf56..04d6c149e 100644 --- a/examples/ruby/lib/twilio-ruby/rest/oauth/v2/token.rb +++ b/examples/ruby/lib/twilio-ruby/rest/oauth/v2/token.rb @@ -23,6 +23,7 @@ class TokenList < ListResource # @return [TokenList] TokenList def initialize(version) super(version) + # Path Solution @solution = {} @uri = "/token" @@ -69,6 +70,53 @@ def create( ) end + ## + # Create the TokenInstanceMetadata + # @param [String] grant_type Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + # @param [String] client_id A 34 character string that uniquely identifies this OAuth App. + # @param [String] client_secret The credential for confidential OAuth App. + # @param [String] code JWT token related to the authorization code grant type. + # @param [String] redirect_uri The redirect uri + # @param [String] audience The targeted audience uri + # @param [String] refresh_token JWT token related to refresh access token. + # @param [String] scope The scope of token + # @return [TokenInstance] Created TokenInstance + def create_with_metadata( + grant_type: :unset, + client_id: :unset, + client_secret: :unset, + code: :unset, + redirect_uri: :unset, + audience: :unset, + refresh_token: :unset, + scope: :unset + ) + data = Twilio::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 = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.create_with_metadata('POST', @uri, data: data, headers: headers) + token_instance = TokenInstance.new( + @version, + response.body, + ) + TokenInstanceMetadata.new( + @version, + token_instance, + response.headers, + response.status_code + ) + end + # Provide a user friendly representation def to_s '#' @@ -104,6 +152,62 @@ def to_s end end + class TokenPageMetadata < PageMetadata + attr_reader :token_page + + def initialize(version, response, solution, limit) + super(version, response) + @token_page = [] + @limit = limit + key = get_key(response.body) + number_of_records = response.body[key].size + while (limit != :unset && number_of_records <= limit) + @token_page << TokenListResponse.new(version, @payload, key) + @payload = self.next_page + break unless @payload + + number_of_records += @payload.body[key].size + end + # Path Solution + @solution = solution + end + + def each + @token_page.each do |record| + yield record + end + end + + def to_s + ''; + end + end + + class TokenListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @token = payload.body[key].map do |data| + TokenInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def token + @token + end + + def headers + @headers + end + + def status_code + @status_code + end + end + class TokenInstance < InstanceResource ## # Initialize the TokenInstance diff --git a/examples/ruby/lib/twilio-ruby/rest/versionless/deployed_devices/fleet.rb b/examples/ruby/lib/twilio-ruby/rest/versionless/deployed_devices/fleet.rb index ab91f9809..1121bf499 100644 --- a/examples/ruby/lib/twilio-ruby/rest/versionless/deployed_devices/fleet.rb +++ b/examples/ruby/lib/twilio-ruby/rest/versionless/deployed_devices/fleet.rb @@ -23,6 +23,7 @@ class FleetList < ListResource # @return [FleetList] FleetList def initialize(version) super(version) + # Path Solution @solution = {} @uri = "/Fleets" @@ -48,6 +49,32 @@ def create( ) end + ## + # Create the FleetInstanceMetadata + # @param [String] name + # @return [FleetInstance] Created FleetInstance + def create_with_metadata( + name: :unset + ) + data = Twilio::Values.of({ + 'Name' => name, + }) + + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.create_with_metadata('POST', @uri, data: data, headers: headers) + fleet_instance = FleetInstance.new( + @version, + response.body, + ) + FleetInstanceMetadata.new( + @version, + fleet_instance, + response.headers, + response.status_code + ) + end + # Provide a user friendly representation def to_s '#' @@ -82,6 +109,26 @@ def fetch ) end + ## + # Fetch the FleetInstanceMetadata + # @return [FleetInstance] Fetched FleetInstance + def fetch_with_metadata + headers = Twilio::Values.of({ 'Content-Type' => 'application/x-www-form-urlencoded', }) + + response = @version.fetch_with_metadata('GET', @uri, headers: headers) + fleet_instance = FleetInstance.new( + @version, + response.body, + sid: @solution[:sid], + ) + FleetInstanceMetadata.new( + @version, + fleet_instance, + response.headers, + response.status_code + ) + end + ## # Provide a user friendly representation def to_s @@ -97,6 +144,53 @@ def inspect end end + class FleetInstanceMetadata < InstanceResourceMetadata + ## + # Initializes a new FleetInstanceMetadata. + # @param [Version] version Version that contains the resource + # @param [}FleetInstance] fleet_instance The instance associated with the metadata. + # @param [Hash] headers Header object with response headers. + # @param [Integer] status_code The HTTP status code of the response. + # @return [FleetInstanceMetadata] The initialized instance with metadata. + def initialize(version, fleet_instance, headers, status_code) + super(version, headers, status_code) + @fleet_instance = fleet_instance + end + + def fleet + @fleet_instance + end + + def headers + @headers + end + + def status_code + @status_code + end + + def to_s + "" + end + end + + class FleetListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @fleet_instance = payload.body[key].map do |data| + FleetInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def fleet_instance + @instance + end + end + class FleetPage < Page ## # Initialize the FleetPage @@ -126,6 +220,62 @@ def to_s end end + class FleetPageMetadata < PageMetadata + attr_reader :fleet_page + + def initialize(version, response, solution, limit) + super(version, response) + @fleet_page = [] + @limit = limit + key = get_key(response.body) + number_of_records = response.body[key].size + while (limit != :unset && number_of_records <= limit) + @fleet_page << FleetListResponse.new(version, @payload, key) + @payload = self.next_page + break unless @payload + + number_of_records += @payload.body[key].size + end + # Path Solution + @solution = solution + end + + def each + @fleet_page.each do |record| + yield record + end + end + + def to_s + ''; + end + end + + class FleetListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @fleet = payload.body[key].map do |data| + FleetInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def fleet + @fleet + end + + def headers + @headers + end + + def status_code + @status_code + end + end + class FleetInstance < InstanceResource ## # Initialize the FleetInstance diff --git a/examples/ruby/lib/twilio-ruby/rest/versionless/understand/assistant.rb b/examples/ruby/lib/twilio-ruby/rest/versionless/understand/assistant.rb index ea7d27c17..ac70c6705 100644 --- a/examples/ruby/lib/twilio-ruby/rest/versionless/understand/assistant.rb +++ b/examples/ruby/lib/twilio-ruby/rest/versionless/understand/assistant.rb @@ -23,6 +23,7 @@ class AssistantList < ListResource # @return [AssistantList] AssistantList def initialize(version) super(version) + # Path Solution @solution = {} @uri = "/Assistants" @@ -67,6 +68,28 @@ def stream(limit: nil, page_size: nil) @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]) end + ## + # Lists AssistantPageMetadata records from the API as a list. + # @param [Integer] limit Upper limit for the number of records to return. stream() + # guarantees to never return more than limit. Default is no limit + # @param [Integer] page_size Number of records to fetch per request, when + # not set will use the default value of 50 records. If no page_size is defined + # but a limit is defined, stream() will attempt to read the limit with the most + # efficient page size, i.e. min(limit, 1000) + # @return [Array] Array of up to limit results + def list_with_metadata(limit: nil, page_size: nil) + limits = @version.read_limits(limit, page_size) + params = Twilio::Values.of({ + + 'PageSize' => page_size, + }); + headers = Twilio::Values.of({}) + + response = @version.page('GET', @uri, params: params, headers: headers) + + AssistantPageMetadata.new(@version, response, @solution, limits[:limit]) + end + ## # When passed a block, yields AssistantInstance records from the API. # This operation lazily loads records as efficiently as possible until the limit @@ -149,6 +172,62 @@ def to_s end end + class AssistantPageMetadata < PageMetadata + attr_reader :assistant_page + + def initialize(version, response, solution, limit) + super(version, response) + @assistant_page = [] + @limit = limit + key = get_key(response.body) + number_of_records = response.body[key].size + while (limit != :unset && number_of_records <= limit) + @assistant_page << AssistantListResponse.new(version, @payload, key) + @payload = self.next_page + break unless @payload + + number_of_records += @payload.body[key].size + end + # Path Solution + @solution = solution + end + + def each + @assistant_page.each do |record| + yield record + end + end + + def to_s + ''; + end + end + + class AssistantListResponse < InstanceListResource + # @param [Array] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @assistant = payload.body[key].map do |data| + AssistantInstance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def assistant + @assistant + end + + def headers + @headers + end + + def status_code + @status_code + end + end + class AssistantInstance < InstanceResource ## # Initialize the AssistantInstance diff --git a/examples/test_spec/twilio_allOf_v1.yaml b/examples/test_spec/twilio_allOf_v1.yaml new file mode 100644 index 000000000..fe822afe2 --- /dev/null +++ b/examples/test_spec/twilio_allOf_v1.yaml @@ -0,0 +1,276 @@ +openapi: 3.1.0 +info: + title: AllOf Test Service + description: Test specification for various allOf scenarios + version: 1.0.0 + contact: + name: 'AllOf Test Service' + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + x-twilio: + apiStandards: v1.0 +servers: + - url: https://allof.test.com +paths: + /v1/basic-allof: + post: + operationId: CreateBasicAllOf + summary: Test basic allOf with multiple schemas + requestBody: + required: true + content: + application/json: + schema: + allOf: + - type: object + required: [ id ] + properties: + id: + type: string + example: "123" + - type: object + required: [ name ] + properties: + name: + type: string + example: "Test Entity" + - type: object + properties: + timestamp: + type: string + format: date-time + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/BasicAllOf' + + /v1/nested-allof: + post: + operationId: CreateNestedAllOf + summary: Test nested allOf + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NestedAllOf' + responses: + '200': + description: Success + + /v1/allof-with-refs: + post: + operationId: CreateAllOfWithRefs + summary: Test allOf with schema references + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AllOfWithRefs' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/AllOfWithRefs' + + /v1/allof-inline-and-ref: + post: + operationId: CreateMixedAllOf + summary: Test allOf mixing inline schemas and refs + requestBody: + required: true + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/BaseEntity' + - type: object + required: [ specificField ] + properties: + specificField: + type: string + extraData: + type: object + responses: + '200': + description: Success + + /v1/allof-with-oneof: + post: + operationId: CreateAllOfWithOneOf + summary: Test allOf combined with oneOf + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AllOfWithOneOf' + responses: + '200': + description: Success + +components: + schemas: + # Basic allOf with refs + BasicAllOf: + allOf: + - $ref: '#/components/schemas/Identifiable' + - $ref: '#/components/schemas/Nameable' + - $ref: '#/components/schemas/Timestamped' + + # Nested allOf + NestedAllOf: + allOf: + - type: object + properties: + outerField: + type: string + - allOf: + - $ref: '#/components/schemas/BaseEntity' + - type: object + properties: + nestedField: + type: string + + # AllOf with multiple schema refs + AllOfWithRefs: + allOf: + - $ref: '#/components/schemas/BaseEntity' + - $ref: '#/components/schemas/Auditable' + - $ref: '#/components/schemas/Versioned' + + # AllOf combined with oneOf + AllOfWithOneOf: + allOf: + - type: object + required: [ entityType ] + properties: + entityType: + type: string + commonField: + type: string + - oneOf: + - $ref: '#/components/schemas/TypeA' + - $ref: '#/components/schemas/TypeB' + + # AllOf with additionalProperties + AllOfWithAdditionalProps: + allOf: + - $ref: '#/components/schemas/BaseEntity' + - type: object + properties: + knownField: + type: string + additionalProperties: + type: string + + # AllOf with discriminator + AllOfWithDiscriminator: + allOf: + - type: object + required: [ objectType ] + properties: + objectType: + type: string + discriminator: + propertyName: objectType + mapping: + cat: '#/components/schemas/Cat' + dog: '#/components/schemas/Dog' + - oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + + # Base schemas + Identifiable: + type: object + required: [ id ] + properties: + id: + type: string + + Nameable: + type: object + required: [ name ] + properties: + name: + type: string + + Timestamped: + type: object + properties: + createdAt: + type: string + format: date-time + updatedAt: + type: string + format: date-time + + BaseEntity: + type: object + required: [ id, createdAt ] + properties: + id: + type: string + createdAt: + type: string + format: date-time + + Auditable: + type: object + properties: + createdBy: + type: string + modifiedBy: + type: string + + Versioned: + type: object + properties: + version: + type: integer + + TypeA: + type: object + required: [ fieldA ] + properties: + fieldA: + type: string + dataA: + type: integer + + TypeB: + type: object + required: [ fieldB ] + properties: + fieldB: + type: boolean + dataB: + type: array + items: + type: string + + Cat: + type: object + properties: + objectType: + type: string + enum: [cat] + meow: + type: boolean + + Dog: + type: object + properties: + objectType: + type: string + enum: [dog] + bark: + type: boolean diff --git a/examples/test_spec/twilio_response_v1.yaml b/examples/test_spec/twilio_response_v1.yaml index 3188edba5..7411ebb9f 100644 --- a/examples/test_spec/twilio_response_v1.yaml +++ b/examples/test_spec/twilio_response_v1.yaml @@ -1,3 +1,407 @@ # This spec tests followings # 1. All types of response body(json) -# 2. Tests paginated response. \ No newline at end of file +# 2. Tests different response structures for each CRUDF operation +# 3. Create - returns created object with metadata +# 4. Read - returns full object with nested details +# 5. Update - returns updated fields with audit info +# 6. Delete - returns deletion confirmation status +# 7. Find/List - returns paginated array with meta + +info: + contact: + email: support@twilio.com + name: Twilio Support + url: https://support.twilio.com + description: This is the public Twilio REST API. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + termsOfService: https://www.twilio.com/legal/tos + title: Twilio - RESPONSE BODY TEST + version: 1.11.0 + x-twilio: + apiStandards: v1.0 +openapi: 3.0.1 + +components: + securitySchemes: + accountSid_authToken: + scheme: basic + type: http + schemas: + # Schema for Create response - includes creation metadata + WidgetCreateResponse: + type: object + properties: + sid: + type: string + description: Unique identifier for the widget + name: + type: string + description: Name of the widget + description: + type: string + description: Description of the widget + date_created: + type: string + format: date-time + description: Timestamp when the widget was created + created_by: + type: string + description: Account SID of the creator + url: + type: string + format: uri + description: URL to fetch this widget + + # Schema for Read response - includes full details with nested objects + WidgetFetchResponse: + type: object + properties: + sid: + type: string + description: Unique identifier for the widget + name: + type: string + description: Name of the widget + description: + type: string + description: Description of the widget + status: + type: string + enum: + - active + - inactive + - archived + description: Current status of the widget + configuration: + type: object + properties: + enabled: + type: boolean + max_capacity: + type: integer + timeout_seconds: + type: integer + retry_policy: + type: object + properties: + max_retries: + type: integer + backoff_multiplier: + type: number + description: Configuration settings for the widget + tags: + type: array + items: + type: string + description: Tags associated with the widget + date_created: + type: string + format: date-time + date_updated: + type: string + format: date-time + url: + type: string + format: uri + + # Schema for Update response - returns updated fields with audit trail + WidgetUpdateResponse: + type: object + properties: + sid: + type: string + description: Unique identifier for the widget + updated_fields: + type: array + items: + type: string + description: List of fields that were updated + previous_values: + type: object + additionalProperties: true + description: Previous values of updated fields + current_values: + type: object + additionalProperties: true + description: Current values of updated fields + date_updated: + type: string + format: date-time + updated_by: + type: string + description: Account SID of the updater + revision: + type: integer + description: Revision number after update + + # Schema for Delete response - returns deletion confirmation + WidgetDeleteResponse: + type: object + properties: + sid: + type: string + description: Unique identifier of the deleted widget + deleted: + type: boolean + description: Whether the deletion was successful + deleted_at: + type: string + format: date-time + description: Timestamp when the widget was deleted + deleted_by: + type: string + description: Account SID of the deleter + message: + type: string + description: Human-readable confirmation message + archive_url: + type: string + format: uri + description: URL to access archived version if available + + # Schema for List item - simplified version for listing + WidgetListResponse: + type: object + properties: + sid: + type: string + name: + type: string + status: + type: string + enum: + - active + - inactive + - archived + date_created: + type: string + format: date-time + url: + type: string + format: uri + +paths: + # CREATE - POST /v1/Widgets + /v1/Widgets: + servers: + - url: https://response.twilio.com + post: + operationId: CreateWidget + description: Create a new Widget resource + security: + - accountSid_authToken: [] + requestBody: + required: true + content: + application/x-www-form-urlencoded: + schema: + type: object + title: CreateWidgetRequest + required: + - Name + properties: + Name: + type: string + description: Name of the widget + Description: + type: string + description: Description of the widget + Status: + type: string + enum: + - active + - inactive + description: Initial status of the widget + responses: + '201': + description: Widget created successfully + content: + application/json: + schema: + $ref: '#/components/schemas/WidgetCreateResponse' + + # FIND/LIST - GET /v1/Widgets + get: + operationId: ListWidget + description: Retrieve a list of all Widgets with pagination + security: + - accountSid_authToken: [] + parameters: + - name: Status + in: query + description: Filter by widget status + required: false + schema: + type: string + enum: + - active + - inactive + - archived + - name: PageSize + in: query + description: Maximum number of items to return in a single response + required: false + schema: + type: integer + minimum: 1 + maximum: 1000 + - name: PageToken + in: query + description: Token for pagination + required: false + schema: + type: string + responses: + '200': + description: List of widgets retrieved successfully + content: + application/json: + schema: + type: object + properties: + widgets: + type: array + items: + $ref: '#/components/schemas/WidgetListResponse' + meta: + type: object + required: + - key + - pageSize + properties: + key: + type: string + description: The key of the list property contains the actual data items + example: "services" + pageSize: + type: integer + description: The actual number of items returned in this response + example: 20 + previousToken: + type: string + description: Token to fetch the previous page of results + example: "eyJwYWdlIjowLCJxdWVyeSI6ImJvb2tzIn0=" + nextToken: + type: string + description: Token to fetch the next page of results + example: "eyJwYWdlIjoyLCJxdWVyeSI6ImJvb2tzIn0=" + + # READ, UPDATE, DELETE - /v1/Widgets/{Sid} + /v1/Widgets/{Sid}: + servers: + - url: https://response.twilio.com + + # READ - GET /v1/Widgets/{Sid} + get: + operationId: FetchWidget + description: Fetch a specific Widget by its SID + security: + - accountSid_authToken: [] + parameters: + - name: Sid + in: path + description: The unique identifier of the Widget + required: true + schema: + type: string + minLength: 34 + maxLength: 34 + pattern: '^WG[0-9a-fA-F]{32}$' + - name: IncludeConfiguration + in: query + description: Whether to include configuration details + required: false + schema: + type: boolean + default: true + responses: + '200': + description: Widget retrieved successfully + content: + application/json: + schema: + $ref: '#/components/schemas/WidgetFetchResponse' + + # UPDATE - POST /v1/Widgets/{Sid} + post: + operationId: UpdateWidget + description: Update a specific Widget by its SID + security: + - accountSid_authToken: [] + parameters: + - name: Sid + in: path + description: The unique identifier of the Widget + required: true + schema: + type: string + minLength: 34 + maxLength: 34 + pattern: '^WG[0-9a-fA-F]{32}$' + requestBody: + required: true + content: + application/x-www-form-urlencoded: + schema: + type: object + title: UpdateWidgetRequest + properties: + Name: + type: string + description: Updated name of the widget + Description: + type: string + description: Updated description of the widget + Status: + type: string + enum: + - active + - inactive + - archived + description: Updated status of the widget + ConfigurationEnabled: + type: boolean + description: Whether widget configuration is enabled + ConfigurationMaxCapacity: + type: integer + description: Maximum capacity setting + responses: + '200': + description: Widget updated successfully + content: + application/json: + schema: + $ref: '#/components/schemas/WidgetUpdateResponse' + + # DELETE - DELETE /v1/Widgets/{Sid} + delete: + operationId: DeleteWidget + description: Delete a specific Widget by its SID + security: + - accountSid_authToken: [] + parameters: + - name: Sid + in: path + description: The unique identifier of the Widget + required: true + schema: + type: string + minLength: 34 + maxLength: 34 + pattern: '^WG[0-9a-fA-F]{32}$' + - name: Archive + in: query + description: Whether to archive instead of permanently delete + required: false + schema: + type: boolean + default: false + responses: + '200': + description: Widget deleted successfully + content: + application/json: + schema: + $ref: '#/components/schemas/WidgetDeleteResponse' diff --git a/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java index 61d5a94c7..c7ce8ff0f 100644 --- a/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java +++ b/src/main/java/com/twilio/oai/AbstractTwilioGoGenerator.java @@ -91,7 +91,22 @@ public void processOpenAPI(final OpenAPI openAPI) { String version = StringHelper.toSnakeCase(twilioCodegen.getVersionFromOpenAPI(openAPI)); twilioCodegen.setDomain(domain); twilioCodegen.setVersion(version); + twilioCodegen.setIsV1ApiStandard(openAPI); twilioCodegen.setOutputDir(domain, version); + + // Make isApiV1 flag available to templates + // Check if this is a Twilio API Standards v1.0 spec + if (openAPI.getInfo().getExtensions() != null && openAPI.getInfo().getExtensions().containsKey("x-twilio")) { + Object xTwilioObj = openAPI.getInfo().getExtensions().get("x-twilio"); + if (xTwilioObj instanceof java.util.Map) { + java.util.Map xTwilio = (java.util.Map) xTwilioObj; + String apiStdVersion = (String) xTwilio.get("apiStandards"); + if (com.twilio.oai.common.ApplicationConstants.isV1.test(apiStdVersion)) { + additionalProperties.put("isApiV1", true); + } + } + } + directoryStructureService.configure(openAPI); if (directoryStructureService.isVersionLess()) { diff --git a/src/main/java/com/twilio/oai/DirectoryStructureService.java b/src/main/java/com/twilio/oai/DirectoryStructureService.java index e2b3e118e..b3b459c1f 100644 --- a/src/main/java/com/twilio/oai/DirectoryStructureService.java +++ b/src/main/java/com/twilio/oai/DirectoryStructureService.java @@ -1,6 +1,7 @@ package com.twilio.oai; import com.twilio.oai.common.Utility; +import com.twilio.oai.java.cache.ResourceCacheContext; import com.twilio.oai.resolver.CaseResolver; import com.twilio.oai.resource.IResourceTree; import com.twilio.oai.resource.Resource; @@ -103,7 +104,10 @@ public void configure(final OpenAPI openAPI) { } updateAccountSidParam(operation); - updatePaginationParams(operation); + if (ResourceCacheContext.get() == null || !ResourceCacheContext.get().isV1() + || (ResourceCacheContext.get().getAdditionalProperties().get(GENERATOR_NAME).equals("twilio-csharp"))) { + updatePaginationParams(operation); + } pathType.ifPresent(type -> Optional .ofNullable(operation.getExtensions()) diff --git a/src/main/java/com/twilio/oai/TwilioCodegenAdapter.java b/src/main/java/com/twilio/oai/TwilioCodegenAdapter.java index c61226574..129290ecd 100644 --- a/src/main/java/com/twilio/oai/TwilioCodegenAdapter.java +++ b/src/main/java/com/twilio/oai/TwilioCodegenAdapter.java @@ -1,5 +1,7 @@ package com.twilio.oai; +import com.twilio.oai.java.cache.ResourceCache2; +import com.twilio.oai.java.cache.ResourceCacheContext; import java.io.File; import java.io.IOException; import java.util.*; @@ -18,7 +20,6 @@ import static com.twilio.oai.common.ApplicationConstants.CONFIG_PATH; -@RequiredArgsConstructor public class TwilioCodegenAdapter { private static final String INPUT_SPEC_PATTERN = "[^_]+_(?.+?)(_(?[^_]+))?\\..+"; @@ -32,6 +33,14 @@ public class TwilioCodegenAdapter { private File toggleFile; private String originalOutputDir; + private final ResourceCache2 resourceCache2 = new ResourceCache2(); + + public TwilioCodegenAdapter(DefaultCodegen codegen, String name) { + this.codegen = codegen; + this.name = name; + ResourceCacheContext.clear(); + ResourceCacheContext.set(resourceCache2); + } public void processOpts() { // Find the templates in the local resources dir. @@ -65,7 +74,7 @@ public void processOpts() { e.printStackTrace(); } } - + public String getVersionFromOpenAPI(final OpenAPI openAPI) { String version = ""; version = StringHelper.camelize(getInputSpecVersion(), true); @@ -83,6 +92,19 @@ public String getVersionFromOpenAPI(final OpenAPI openAPI) { return version; } + public void setIsV1ApiStandard (final OpenAPI openAPI) { + String apiStdVersion = null; + if (openAPI.getInfo().getExtensions() != null && openAPI.getInfo().getExtensions().containsKey("x-twilio")) { + Object xTwilioObj = openAPI.getInfo().getExtensions().get("x-twilio"); + if (xTwilioObj instanceof Map) { + Map xTwilio = (Map) xTwilioObj; + apiStdVersion = (String) xTwilio.get("apiStandards"); + } + } + boolean isV1 = ApplicationConstants.isV1.test(apiStdVersion); + ResourceCacheContext.get().setV1(isV1); + } + public void setDomain(final String domain) { final String domainPackage = domain.replaceAll("[-.]", ""); setOutputDir(domainPackage, getInputSpecVersion()); @@ -90,7 +112,7 @@ public void setDomain(final String domain) { codegen.additionalProperties().put("domainName", StringHelper.camelize(domain)); codegen.additionalProperties().put("domainPackage", domainPackage); } - + public void setVersion(final String version) { codegen.additionalProperties().put("clientVersion", version); codegen.additionalProperties().put(DirectoryStructureService.API_VERSION, version); diff --git a/src/main/java/com/twilio/oai/TwilioCsharpGenerator.java b/src/main/java/com/twilio/oai/TwilioCsharpGenerator.java index d44c537f3..90f295c1a 100644 --- a/src/main/java/com/twilio/oai/TwilioCsharpGenerator.java +++ b/src/main/java/com/twilio/oai/TwilioCsharpGenerator.java @@ -4,9 +4,11 @@ import com.samskivert.mustache.Mustache; import com.twilio.oai.api.CsharpApiResourceBuilder; import com.twilio.oai.api.CsharpApiResources; +import com.twilio.oai.common.ApplicationConstants; import com.twilio.oai.common.EnumConstants; import com.twilio.oai.common.LanguageDataType; import com.twilio.oai.common.Utility; +import com.twilio.oai.java.cache.ResourceCacheContext; import com.twilio.oai.templating.mustache.TitleCaseLambda; import com.twilio.oai.resolver.IConventionMapper; import com.twilio.oai.resolver.LanguageConventionResolver; @@ -56,7 +58,6 @@ public class TwilioCsharpGenerator extends CSharpClientCodegen { private final Map modelFormatMap = new HashMap<>(); private final List allModels = new ArrayList<>(); private final IConventionMapper conventionMapper = new LanguageConventionResolver(CONFIG_CSHARP_JSON_PATH); - private final IApiActionTemplate apiActionTemplate = new CsharpApiActionTemplate(this); public TwilioCsharpGenerator() { super(); @@ -87,7 +88,7 @@ private CsharpApiResources processCodegenOperations(List opLis CsharpSerializer csharpSerializer = new CsharpSerializer(conventionMapper); CsharpCodegenParameterDataTypeResolver csharpCodegenParameterDataTypeResolver = new CsharpCodegenParameterDataTypeResolver(conventionMapper, csharpSerializer); CodegenParameterResolver codegenParameterResolver = new CodegenParameterResolver(languageDataType, csharpCodegenParameterDataTypeResolver, codegenModelResolver); - + IApiActionTemplate apiActionTemplate = new CsharpApiActionTemplate(this); return new CsharpApiResourceBuilder(apiActionTemplate, opList, this.allModels) .updateApiPath() @@ -108,11 +109,14 @@ public void processOpts() { @Override public void processOpenAPI(final OpenAPI openAPI) { + ResourceCacheContext.get().clear(); + ResourceCacheContext.get().getAdditionalProperties().put(ApplicationConstants.GENERATOR_NAME, getName()); String domain = StringHelper.camelize(twilioCodegen.getDomainFromOpenAPI(openAPI)); String version = StringHelper.camelize(twilioCodegen.getVersionFromOpenAPI(openAPI)); twilioCodegen.setDomain(domain); twilioCodegen.setVersion(version); twilioCodegen.setOutputDir(domain, version); + twilioCodegen.setIsV1ApiStandard(openAPI); directoryStructureService.configure(openAPI); } diff --git a/src/main/java/com/twilio/oai/TwilioGoGenerator.java b/src/main/java/com/twilio/oai/TwilioGoGenerator.java index bcbd51a4b..8cadfa962 100644 --- a/src/main/java/com/twilio/oai/TwilioGoGenerator.java +++ b/src/main/java/com/twilio/oai/TwilioGoGenerator.java @@ -91,12 +91,32 @@ String removeDigits(String modelName) { String modelNameWithoutStatusCode(String modelName) { if(modelName == null || modelName.isEmpty()) return modelName; + + // Don't process primitive types or array types + if (isPrimitiveOrArrayType(modelName)) { + return modelName; + } + String newModelName = removeStatusCode(modelName); if(Objects.equals(newModelName, modelName)) newModelName = removeDigits(newModelName); return StringUtils.camelize(newModelName); } + private boolean isPrimitiveOrArrayType(String typeName) { + if (typeName == null) return false; + // Check for array types + if (typeName.startsWith("[]")) return true; + // Check for Go primitive types + String[] primitiveTypes = {"string", "int", "int32", "int64", "float32", "float64", "bool", "byte", "rune", "array", "map"}; + for (String primitive : primitiveTypes) { + if (typeName.equals(primitive) || typeName.startsWith(primitive + " ") || typeName.startsWith("map[")) { + return true; + } + } + return false; + } + private boolean contains2xxStatusCode(String modelName) { return Pattern.compile("2\\d{2}_").matcher(modelName).find(); } @@ -132,6 +152,87 @@ public Map updateAllModels(Map objs) { updatedObjs.put(key, value); }); + // Fix all property references to models with status codes + updatedObjs.forEach((key, value) -> { + ModelMap modelMap = value.getModels().get(0); + CodegenModel model = modelMap.getModel(); + // Update all property dataTypes that reference models with status codes + boolean modified = false; + + for (CodegenProperty property : model.allVars) { + // Check if property type needs status code removal (with or without underscores) + String cleanedDataType = modelNameWithoutStatusCode(property.dataType); + if (!cleanedDataType.equals(property.dataType)) { + property.dataType = cleanedDataType; + modified = true; + } + + // Update vendor extension used in Go templates + if (property.vendorExtensions.containsKey("x-go-base-type")) { + String baseType = (String) property.vendorExtensions.get("x-go-base-type"); + String cleanedBaseType = modelNameWithoutStatusCode(baseType); + if (!cleanedBaseType.equals(baseType)) { + property.vendorExtensions.put("x-go-base-type", cleanedBaseType); + modified = true; + } + } + + // Also check baseType + if (property.baseType != null) { + String cleanedBaseType = modelNameWithoutStatusCode(property.baseType); + if (!cleanedBaseType.equals(property.baseType)) { + property.baseType = cleanedBaseType; + modified = true; + } + } + + // Check complexType + if (property.complexType != null) { + String cleanedComplexType = modelNameWithoutStatusCode(property.complexType); + if (!cleanedComplexType.equals(property.complexType)) { + property.complexType = cleanedComplexType; + modified = true; + } + } + } + // Update vars list as well (in addition to allVars) + for (CodegenProperty property : model.vars) { + String cleanedDataType = modelNameWithoutStatusCode(property.dataType); + if (!cleanedDataType.equals(property.dataType)) { + property.dataType = cleanedDataType; + modified = true; + } + + if (property.vendorExtensions.containsKey("x-go-base-type")) { + String baseType = (String) property.vendorExtensions.get("x-go-base-type"); + String cleanedBaseType = modelNameWithoutStatusCode(baseType); + if (!cleanedBaseType.equals(baseType)) { + property.vendorExtensions.put("x-go-base-type", cleanedBaseType); + modified = true; + } + } + + if (property.baseType != null) { + String cleanedBaseType = modelNameWithoutStatusCode(property.baseType); + if (!cleanedBaseType.equals(property.baseType)) { + property.baseType = cleanedBaseType; + modified = true; + } + } + + if (property.complexType != null) { + String cleanedComplexType = modelNameWithoutStatusCode(property.complexType); + if (!cleanedComplexType.equals(property.complexType)) { + property.complexType = cleanedComplexType; + modified = true; + } + } + } + if (modified) { + modelMap.setModel(model); + } + }); + return updatedObjs; } @@ -197,6 +298,12 @@ public OperationsMap postProcessOperationsWithModels(final OperationsMap objs, L Utility.populateCrudOperations(co); Utility.resolveContentType(co); co.returnType = modelNameWithoutStatusCode(co.returnType); + + // Add isApiV1 flag for template usage + if (com.twilio.oai.java.cache.ResourceCacheContext.get() != null && com.twilio.oai.java.cache.ResourceCacheContext.get().isV1()) { + co.vendorExtensions.put("isApiV1", true); + } + if (co.nickname.startsWith("List")) { // make sure the format matches the other methods co.vendorExtensions.put("x-domain-name", co.nickname.replaceFirst("List", "")); diff --git a/src/main/java/com/twilio/oai/TwilioPhpGenerator.java b/src/main/java/com/twilio/oai/TwilioPhpGenerator.java index 201c45c09..f247e407b 100644 --- a/src/main/java/com/twilio/oai/TwilioPhpGenerator.java +++ b/src/main/java/com/twilio/oai/TwilioPhpGenerator.java @@ -5,8 +5,11 @@ import com.twilio.oai.api.PhpApiResourceBuilder; import com.twilio.oai.api.PhpApiResources; import com.twilio.oai.api.PhpDomainBuilder; +import com.twilio.oai.common.ApplicationConstants; import com.twilio.oai.common.EnumConstants; import com.twilio.oai.common.Utility; +import com.twilio.oai.java.cache.ResourceCache2; +import com.twilio.oai.java.cache.ResourceCacheContext; import com.twilio.oai.resolver.IConventionMapper; import com.twilio.oai.resolver.LanguageConventionResolver; import com.twilio.oai.resolver.common.CodegenModelResolver; @@ -28,7 +31,6 @@ public class TwilioPhpGenerator extends PhpClientCodegen { - public static final String VALUES = "values"; public static final String JSON_INGRESS = "json_ingress"; private static final String PHP_CONVENTIONAL_MAP_PATH = "config/" + EnumConstants.Generator.TWILIO_PHP.getValue() + ".json"; @@ -73,12 +75,15 @@ public void processOpts() { } @Override + @SuppressWarnings("unchecked") public void processOpenAPI(final OpenAPI openAPI) { + String domain = StringHelper.camelize(twilioCodegen.getDomainFromOpenAPI(openAPI)); String version = StringHelper.camelize(twilioCodegen.getVersionFromOpenAPI(openAPI)); twilioCodegen.setDomain(domain); twilioCodegen.setVersion(version); twilioCodegen.setOutputDir(domain, version); + twilioCodegen.setIsV1ApiStandard(openAPI); setSrcBasePath(""); directoryStructureService.configureResourceFamily(openAPI); @@ -129,9 +134,27 @@ public OperationsMap postProcessOperationsWithModels(final OperationsMap objs, L final List opList = directoryStructureService.processOperations(results); PhpApiResources apiResources = processCodegenOperations(opList); results.put("resources", apiResources); + + // Generate dynamic instance class files (one per response model) + generateDynamicInstanceFiles(apiResources, results); + return results; } + private void generateDynamicInstanceFiles(PhpApiResources apiResources, OperationsMap objs) { + // Build base context with all properties needed by the template + Map baseContext = new HashMap<>(); + baseContext.putAll(additionalProperties); + baseContext.put("resources", apiResources); + // domainName and version are already in additionalProperties (set by TwilioCodegenAdapter) + + // Get output directory for API files + String outputDir = apiFileFolder(); + + // Generate the dynamic files + phpApiActionTemplate.generateDynamicFiles(baseContext, outputDir); + } + @Override public String getName() { return EnumConstants.Generator.TWILIO_PHP.getValue(); @@ -157,14 +180,26 @@ private PhpApiResources processCodegenOperations(List opList) CodegenModelResolver codegenModelResolver = new CodegenModelResolver(conventionMapper, modelFormatMap, Arrays.asList(EnumConstants.JavaDataTypes.values())); PhpPropertyResolver phpPropertyResolver = new PhpPropertyResolver(conventionMapper); - return new PhpApiResourceBuilder(phpApiActionTemplate, opList, this.allModels, twilioCodegen.getToggles(JSON_INGRESS), phpPropertyResolver) - .addVersionLessTemplates(openAPI, directoryStructureService) + + // Create the builder and configure it + PhpApiResourceBuilder builder = new PhpApiResourceBuilder(phpApiActionTemplate, opList, this.allModels, twilioCodegen.getToggles(JSON_INGRESS), phpPropertyResolver); + builder.addVersionLessTemplates(openAPI, directoryStructureService) .updateAdditionalProps(directoryStructureService) .updateOperations(phpParameterResolver) .updateResponseModel(phpPropertyResolver, codegenModelResolver) .updateTemplate() .updateApiPath() - .setImports(directoryStructureService) - .build(); + .setImports(directoryStructureService); + + // Build the apiResource + PhpApiResources apiResources = builder.build(); + + // Register dynamic templates with the full apiResource if there are multiple response models + // This must be done after build() so the apiResource has all properties set + if (builder.hasMultipleResponseModels()) { + phpApiActionTemplate.addDynamicTemplates(PhpApiActionTemplate.TEMPLATE_TYPE_INSTANCE_CLASS, apiResources); + } + + return apiResources; } } diff --git a/src/main/java/com/twilio/oai/TwilioPythonGenerator.java b/src/main/java/com/twilio/oai/TwilioPythonGenerator.java index 74dfb785a..46d31d0f1 100644 --- a/src/main/java/com/twilio/oai/TwilioPythonGenerator.java +++ b/src/main/java/com/twilio/oai/TwilioPythonGenerator.java @@ -77,6 +77,7 @@ public void processOpenAPI(final OpenAPI openAPI) { String version = StringHelper.toSnakeCase(twilioCodegen.getVersionFromOpenAPI(openAPI)); twilioCodegen.setDomain(domain); twilioCodegen.setVersion(version); + twilioCodegen.setIsV1ApiStandard(openAPI); twilioCodegen.setOutputDir(domain, version); openAPI.getPaths().forEach(resourceTree::addResource); diff --git a/src/main/java/com/twilio/oai/TwilioRubyGenerator.java b/src/main/java/com/twilio/oai/TwilioRubyGenerator.java index 7bf5c07cd..c6163bd71 100644 --- a/src/main/java/com/twilio/oai/TwilioRubyGenerator.java +++ b/src/main/java/com/twilio/oai/TwilioRubyGenerator.java @@ -2,8 +2,10 @@ import com.twilio.oai.api.RubyApiResourceBuilder; import com.twilio.oai.api.RubyApiResources; +import com.twilio.oai.common.ApplicationConstants; import com.twilio.oai.common.EnumConstants; import com.twilio.oai.common.Utility; +import com.twilio.oai.java.cache.ResourceCacheContext; import com.twilio.oai.resolver.IConventionMapper; import com.twilio.oai.resolver.LanguageConventionResolver; import com.twilio.oai.resolver.common.CodegenModelResolver; @@ -16,6 +18,7 @@ import com.twilio.oai.template.RubyApiActionTemplate; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.PathItem; +import java.util.LinkedHashMap; import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.CodegenOperation; import org.openapitools.codegen.languages.RubyClientCodegen; @@ -46,7 +49,13 @@ public TwilioRubyGenerator() { @Override public void processOpenAPI(final OpenAPI openAPI) { - + String apiStdVersion = null; + if (openAPI.getInfo().getExtensions() != null && openAPI.getInfo().getExtensions().containsKey("x-twilio")) { + LinkedHashMap xTwilio = (LinkedHashMap)openAPI.getInfo().getExtensions().get("x-twilio"); + apiStdVersion = (String) xTwilio.get("apiStandards"); + } + boolean isV1 = ApplicationConstants.isV1.test(apiStdVersion); + ResourceCacheContext.get().setV1(isV1); String domain = StringHelper.toSnakeCase(twilioCodegen.getDomainFromOpenAPI(openAPI)); String version = StringHelper.toSnakeCase(twilioCodegen.getVersionFromOpenAPI(openAPI)); twilioCodegen.setDomain(domain); diff --git a/src/main/java/com/twilio/oai/api/ApiResourceBuilder.java b/src/main/java/com/twilio/oai/api/ApiResourceBuilder.java index 355268a87..47e2820e6 100644 --- a/src/main/java/com/twilio/oai/api/ApiResourceBuilder.java +++ b/src/main/java/com/twilio/oai/api/ApiResourceBuilder.java @@ -30,6 +30,7 @@ public abstract class ApiResourceBuilder implements IApiResourceBuilder { protected final Map modelTree = new TreeMap<>(); protected final List requiredPathParams = new ArrayList<>(); protected Set apiResponseModels = new LinkedHashSet<>(); + protected Set responseInstanceModels = new LinkedHashSet<>(); protected final Map metaAPIProperties = new HashMap<>(); protected final List listOperations = new ArrayList<>(); protected final List instanceOperations = new ArrayList<>(); @@ -231,6 +232,8 @@ protected Map mapOperation(CodegenOperation operation) { addOperationName(operation, Operation.FETCH.getValue()); } else if (StringUtils.startsWithIgnoreCase(operation.operationId, "list")) { addOperationName(operation, Operation.READ.getValue()); + } else if (StringUtils.startsWithIgnoreCase(operation.operationId, "patch")) { + addOperationName(operation, Operation.PATCH.getValue()); } operationMap.put("hasRequiredNonPathParams", diff --git a/src/main/java/com/twilio/oai/api/ApiResources.java b/src/main/java/com/twilio/oai/api/ApiResources.java index ea4209d29..0b982ef67 100644 --- a/src/main/java/com/twilio/oai/api/ApiResources.java +++ b/src/main/java/com/twilio/oai/api/ApiResources.java @@ -5,6 +5,7 @@ import java.util.Map; import java.util.Set; +import com.twilio.oai.java.cache.ResourceCacheContext; import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.CodegenOperation; import org.openapitools.codegen.CodegenParameter; @@ -17,12 +18,14 @@ public class ApiResources { String recordKey; String version; List responseModels; + Set responseInstanceModels; List requiredPathParams; List apiOperations; Map metaProperties; String namespaceSubPart; boolean hasPaginationOperation; Set nestedModels; + private Boolean isApiV1 = null; // true or NULL public ApiResources(ApiResourceBuilder apiResourceBuilder) { apiOperations = apiResourceBuilder.codegenOperationList; @@ -36,5 +39,9 @@ public ApiResources(ApiResourceBuilder apiResourceBuilder) { namespaceSubPart = apiResourceBuilder.namespaceSubPart; hasPaginationOperation = apiResourceBuilder.hasPaginationOperation(); nestedModels = apiResourceBuilder.nestedModels; + if (ResourceCacheContext.get() != null && ResourceCacheContext.get().isV1()) { + isApiV1 = true; + } + responseInstanceModels = apiResourceBuilder.responseInstanceModels; } } diff --git a/src/main/java/com/twilio/oai/api/CsharpApiResourceBuilder.java b/src/main/java/com/twilio/oai/api/CsharpApiResourceBuilder.java index 9f3682487..d98426ff2 100644 --- a/src/main/java/com/twilio/oai/api/CsharpApiResourceBuilder.java +++ b/src/main/java/com/twilio/oai/api/CsharpApiResourceBuilder.java @@ -8,6 +8,7 @@ import com.twilio.oai.common.EnumConstants.CsharpHttpMethod; import com.twilio.oai.common.EnumConstants.CsharpDataTypes; import com.twilio.oai.common.Utility; +import com.twilio.oai.java.cache.ResourceCacheContext; import com.twilio.oai.resolver.Resolver; import com.twilio.oai.resolver.common.CodegenModelOneOf; import com.twilio.oai.resolver.csharp.OperationStore; @@ -41,6 +42,14 @@ public class CsharpApiResourceBuilder extends ApiResourceBuilder { public String authMethod = ""; CodegenModelOneOf codegenModelOneOf = CodegenModelOneOf.getInstance(); + + // Operation-specific response models for V1 + protected List createResponseModels = new ArrayList<>(); + protected List updateResponseModels = new ArrayList<>(); + protected List patchResponseModels = new ArrayList<>(); + protected List listResponseModels = new ArrayList<>(); + protected List fetchResponseModels = new ArrayList<>(); + /** * List of C# primitive types that require a nullable marker (?) when nullable */ @@ -278,6 +287,10 @@ private void recursivelyResolve(CodegenProperty codegenProperty) { @Override public ApiResourceBuilder updateResponseModel(Resolver codegenPropertyIResolver, Resolver codegenModelResolver) { + if (ResourceCacheContext.get().isV1()) { + updateResponseModelV1(codegenModelResolver); + return this; + } List responseModels = new ArrayList<>(); codegenOperationList.forEach(codegenOperation -> { codegenOperation.responses.forEach(response -> { @@ -302,6 +315,45 @@ public ApiResourceBuilder updateResponseModel(Resolver codegenP return this; } + private void updateResponseModelV1(Resolver codegenModelResolver) { + codegenOperationList.forEach(codegenOperation -> { + List responseModels = new ArrayList<>(); + codegenOperation.responses.forEach(response -> { + String modelName = response.dataType; + if (response.dataType != null && response.dataType.startsWith(EnumConstants.CsharpDataTypes.LIST.getValue())) { + modelName = response.baseType; + } + Optional responseModel = Utility.getModel(allModels, modelName, recordKey, codegenOperation); + if ((responseModel == null) || responseModel.isEmpty() || (Integer.parseInt(response.code) >= 400)) { + return; + } + CodegenModel codegenModel = responseModel.get(); + for (CodegenProperty property : codegenModel.vars) { + recursivelyResolve(property); + } + codegenModelResolver.resolve(codegenModel, this); + responseModels.add(codegenModel); + Set distinctResponseModel = getDistinctResponseModel(responseModels); + + String operationId = codegenOperation.operationId.toLowerCase(); + if (operationId.isEmpty()) { + throw new RuntimeException("Csharp: Operation ID is missing for an operation."); + } + if (operationId.toLowerCase().startsWith("create")) { + this.createResponseModels.addAll(new ArrayList<>(distinctResponseModel)); + } else if (operationId.toLowerCase().startsWith("update")) { + this.updateResponseModels.addAll(new ArrayList<>(distinctResponseModel)); + } else if (operationId.toLowerCase().startsWith("patch")) { + this.patchResponseModels.addAll(new ArrayList<>(distinctResponseModel)); + } else if (operationId.toLowerCase().startsWith("list")) { + this.listResponseModels.addAll(new ArrayList<>(distinctResponseModel)); + } else if (operationId.toLowerCase().startsWith("fetch")) { + this.fetchResponseModels.addAll(new ArrayList<>(distinctResponseModel)); + } + }); + }); + } + public Set getDistinctResponseModel(List responseModels) { HashMap propertyMap = new HashMap<>(); Set distinctResponseModels = new LinkedHashSet<>(); diff --git a/src/main/java/com/twilio/oai/api/CsharpApiResources.java b/src/main/java/com/twilio/oai/api/CsharpApiResources.java index e790d8fbf..3995ff517 100644 --- a/src/main/java/com/twilio/oai/api/CsharpApiResources.java +++ b/src/main/java/com/twilio/oai/api/CsharpApiResources.java @@ -4,6 +4,7 @@ import com.twilio.oai.resolver.csharp.OperationStore; import lombok.Getter; import lombok.Setter; +import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.IJsonSchemaValidationProperties; import java.util.ArrayList; @@ -13,11 +14,23 @@ public class CsharpApiResources extends ApiResources { @Getter @Setter private String authMethod; @Getter @Setter private String restClientMethodName; @Getter @Setter private String clientName; + + List createResponseModels; + List updateResponseModels; + List listResponseModels; + List patchResponseModels; + List fetchResponseModels; List enums = new ArrayList<>(OperationStore.getInstance().getEnums().values()); public String resourceConstant = ApplicationConstants.RESOURCE; - public CsharpApiResources(ApiResourceBuilder apiResourceBuilder) { + public CsharpApiResources(CsharpApiResourceBuilder apiResourceBuilder) { super(apiResourceBuilder); + this.authMethod = apiResourceBuilder.authMethod; + this.createResponseModels = apiResourceBuilder.createResponseModels; + this.updateResponseModels = apiResourceBuilder.updateResponseModels; + this.patchResponseModels = apiResourceBuilder.patchResponseModels; + this.listResponseModels = apiResourceBuilder.listResponseModels; + this.fetchResponseModels = apiResourceBuilder.fetchResponseModels; } } diff --git a/src/main/java/com/twilio/oai/api/PhpApiResourceBuilder.java b/src/main/java/com/twilio/oai/api/PhpApiResourceBuilder.java index 06fc152ba..6245538a8 100644 --- a/src/main/java/com/twilio/oai/api/PhpApiResourceBuilder.java +++ b/src/main/java/com/twilio/oai/api/PhpApiResourceBuilder.java @@ -2,6 +2,7 @@ import com.twilio.oai.*; import com.twilio.oai.common.EnumConstants; +import com.twilio.oai.java.cache.ResourceCacheContext; import com.twilio.oai.resolver.IConventionMapper; import com.twilio.oai.resolver.LanguageConventionResolver; import com.twilio.oai.resolver.Resolver; @@ -58,7 +59,16 @@ public PhpApiResourceBuilder updateTemplate() { template.add(PhpApiActionTemplate.TEMPLATE_TYPE_OPTIONS); template.add(PhpApiActionTemplate.TEMPLATE_TYPE_PAGE); template.add(PhpApiActionTemplate.TEMPLATE_TYPE_LIST); - template.add(PhpApiActionTemplate.TEMPLATE_TYPE_INSTANCE); + + // Only add regular instance template when there's 1 or fewer response models + // OR when isApiV1 is false (dynamic templates only work with API V1 standard) + // When there are multiple distinct response models AND isApiV1 is true, dynamic templates will be + // added after build() in the generator with the full apiResource + boolean isApiV1 = ResourceCacheContext.get() != null && ResourceCacheContext.get().isV1(); + if (!isApiV1 || responseInstanceModels == null || responseInstanceModels.size() <= 1) { + template.add(PhpApiActionTemplate.TEMPLATE_TYPE_INSTANCE); + } + // if any operation in current op list(CRUDF) has application/json request body type if (!nestedModels.isEmpty()) template.add(PhpApiActionTemplate.TEMPLATE_TYPE_MODELS); @@ -66,6 +76,16 @@ public PhpApiResourceBuilder updateTemplate() { return this; } + /** + * Returns true if this builder has multiple distinct response models that require + * separate instance class files AND isApiV1 is true. + * Dynamic instance templates are only generated for API V1 standard specs. + */ + public boolean hasMultipleResponseModels() { + boolean isApiV1 = ResourceCacheContext.get() != null && ResourceCacheContext.get().isV1(); + return isApiV1 && responseInstanceModels != null && responseInstanceModels.size() > 1; + } + @Override public PhpApiResources build() { return new PhpApiResources(this); @@ -378,6 +398,7 @@ private static Set extractConditionalParams(CodegenOperation operation) @Override public ApiResourceBuilder updateResponseModel(Resolver codegenPropertyResolver) { List responseModels = new ArrayList<>(); + Set responseInstanceModels = new HashSet<>(); codegenOperationList.forEach(codegenOperation -> { codegenOperation.responses .stream() @@ -392,8 +413,10 @@ public ApiResourceBuilder updateResponseModel(Resolver codegenP item.vars.forEach(e -> codegenPropertyResolver.resolve(e, this)); item.allVars.forEach(e -> codegenPropertyResolver.resolve(e, this)); responseModels.add(item); + responseInstanceModels.add(item); }); }); + this.responseInstanceModels = responseInstanceModels; this.apiResponseModels = getDistinctResponseModel(responseModels); return this; } diff --git a/src/main/java/com/twilio/oai/api/RubyApiResources.java b/src/main/java/com/twilio/oai/api/RubyApiResources.java index 15b4b0c42..1392ca4ff 100644 --- a/src/main/java/com/twilio/oai/api/RubyApiResources.java +++ b/src/main/java/com/twilio/oai/api/RubyApiResources.java @@ -1,5 +1,6 @@ package com.twilio.oai.api; +import com.twilio.oai.java.cache.ResourceCacheContext; import org.openapitools.codegen.CodegenParameter; import java.util.ArrayList; @@ -10,11 +11,15 @@ public class RubyApiResources extends FluentApiResources { private List readParams; List parentDir = new ArrayList<>(); boolean hasParents = false; + private Boolean isApiV1 = null; public RubyApiResources(RubyApiResourceBuilder apiResourceBuilder) { super(apiResourceBuilder); this.readParams = apiResourceBuilder.readParams; this.parentDir = apiResourceBuilder.parentDir; this.hasParents = apiResourceBuilder.hasParents; + if (ResourceCacheContext.get() != null && ResourceCacheContext.get().isV1()) { + isApiV1 = true; + } } } diff --git a/src/main/java/com/twilio/oai/common/ApplicationConstants.java b/src/main/java/com/twilio/oai/common/ApplicationConstants.java index ba5c08dd5..6b396062c 100644 --- a/src/main/java/com/twilio/oai/common/ApplicationConstants.java +++ b/src/main/java/com/twilio/oai/common/ApplicationConstants.java @@ -65,6 +65,7 @@ public class ApplicationConstants { public static final String X_MODEL_TYPE = "x-model-type"; // EnumConstants.OpenApiEnumType public static final String X_IS_MODEL = "x-is-model"; public static final String X_REQUEST_CONTENT_TYPE = "x-request-content-type"; + public static final String GENERATOR_NAME = "generator-name"; public static final Predicate isV1 = input -> input != null && input.startsWith("v1"); // Usage: isV1.test("v1.0"); } diff --git a/src/main/java/com/twilio/oai/common/EnumConstants.java b/src/main/java/com/twilio/oai/common/EnumConstants.java index 606bc9be7..4365faaef 100644 --- a/src/main/java/com/twilio/oai/common/EnumConstants.java +++ b/src/main/java/com/twilio/oai/common/EnumConstants.java @@ -32,7 +32,8 @@ public enum Operation { DELETE("Delete"), - READ("Read"); + READ("Read"), + PATCH("Patch"); private final String value; } diff --git a/src/main/java/com/twilio/oai/java/cache/ResourceCache2.java b/src/main/java/com/twilio/oai/java/cache/ResourceCache2.java index d8a06e1ee..23d2dd5f9 100644 --- a/src/main/java/com/twilio/oai/java/cache/ResourceCache2.java +++ b/src/main/java/com/twilio/oai/java/cache/ResourceCache2.java @@ -35,6 +35,10 @@ public class ResourceCache2 { @Getter @Setter private boolean isV1; + + @Getter + @Setter + private HashMap additionalProperties = new HashMap<>(); public void setAllModelsByDefaultGenerator(ArrayList allModelsByDefaultGenerator) { this.allModelsByDefaultGenerator = new ArrayList<>(allModelsByDefaultGenerator); diff --git a/src/main/java/com/twilio/oai/template/AbstractApiActionTemplate.java b/src/main/java/com/twilio/oai/template/AbstractApiActionTemplate.java index 7864629e6..e9549c5f3 100644 --- a/src/main/java/com/twilio/oai/template/AbstractApiActionTemplate.java +++ b/src/main/java/com/twilio/oai/template/AbstractApiActionTemplate.java @@ -1,12 +1,16 @@ package com.twilio.oai.template; -import java.io.File; -import java.util.List; -import java.util.Map; - +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.SupportingFile; +import java.io.*; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.util.*; + public abstract class AbstractApiActionTemplate implements IApiActionTemplate { public static final String API_TEMPLATE = "api"; public static final String NESTED_MODELS = "nested_models"; @@ -15,6 +19,22 @@ public abstract class AbstractApiActionTemplate implements IApiActionTemplate { private final Map> templates = mapping(); protected final CodegenConfig codegen; + // Store dynamic template data + protected final Map dynamicTemplates = new LinkedHashMap<>(); + + // Inner class to hold dynamic template configuration + protected static class DynamicTemplateData { + String templateFile; + String fileSuffix; + Object apiResource; // The full apiResource object (e.g., PhpApiResources) + + DynamicTemplateData(String templateFile, String fileSuffix, Object apiResource) { + this.templateFile = templateFile; + this.fileSuffix = fileSuffix; + this.apiResource = apiResource; + } + } + protected AbstractApiActionTemplate(CodegenConfig defaultCodegen) { this.codegen = initialise(defaultCodegen); } @@ -33,6 +53,7 @@ public void clean() { for (final List entry : templates.values()) { codegen.apiTemplateFiles().remove(entry.get(0)); } + dynamicTemplates.clear(); } @Override @@ -41,6 +62,152 @@ public void add(String template) { codegen.apiTemplateFiles().put(templateStrings.get(0), templateStrings.get(1)); } + @Override + public void addDynamicTemplates(String templateType, Object apiResource) { + List templateStrings = templates.get(templateType); + if (templateStrings != null && apiResource != null) { + // Check if apiResource has responseInstanceModels with more than 1 model + Set models = getResponseInstanceModels(apiResource); + if (models != null && models.size() > 1) { + dynamicTemplates.put(templateType, new DynamicTemplateData( + templateStrings.get(0), // template file + templateStrings.get(1), // file suffix + apiResource + )); + } + } + } + + @Override + public void generateDynamicFiles(Map baseContext, String outputDir) { + for (Map.Entry entry : dynamicTemplates.entrySet()) { + DynamicTemplateData data = entry.getValue(); + + // Extract responseInstanceModels from apiResource + Set models = getResponseInstanceModels(data.apiResource); + if (models == null || models.isEmpty()) { + continue; + } + + for (CodegenModel model : models) { + try { + // Build context with apiResource as "resources" + // The template uses {{#resources}} wrapper, so we need to provide the apiResource + // but with responseInstanceModels containing only the current model + Map context = new HashMap<>(baseContext); + + // Create a wrapper that provides all apiResource properties + // but overrides responseInstanceModels with just the current model + Map resourcesMap = new HashMap<>(); + copyObjectProperties(data.apiResource, resourcesMap); + // Override responseInstanceModels with single model + resourcesMap.put("responseInstanceModels", Collections.singleton(model)); + context.put("resources", resourcesMap); + + // Read and compile template + String templateContent = readResourceTemplate(data.templateFile); + Template template = Mustache.compiler() + .withLoader(name -> new StringReader(readResourceTemplate(name + ".mustache"))) + .defaultValue("") + .compile(templateContent); + + // Render + String rendered = template.execute(context); + + // Write file: {outputDir}/{ModelClassname}{suffix} + String filename = outputDir + File.separator + model.classname + data.fileSuffix; + writeFile(filename, rendered); + + System.out.println("Generated dynamic file: " + filename); + + } catch (Exception e) { + System.err.println("Error generating dynamic file for " + model.classname + ": " + e.getMessage()); + e.printStackTrace(); + } + } + } + } + + /** + * Extracts responseInstanceModels from an apiResource object using reflection. + */ + @SuppressWarnings("unchecked") + private Set getResponseInstanceModels(Object apiResource) { + if (apiResource == null) return null; + + try { + Field field = findField(apiResource.getClass(), "responseInstanceModels"); + if (field != null) { + field.setAccessible(true); + Object value = field.get(apiResource); + if (value instanceof Set) { + return (Set) value; + } + } + } catch (Exception e) { + // Ignore and return null + } + return null; + } + + /** + * Finds a field by name in the class hierarchy. + */ + private Field findField(Class clazz, String fieldName) { + while (clazz != null) { + try { + return clazz.getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { + clazz = clazz.getSuperclass(); + } + } + return null; + } + + /** + * Copies all properties from an object to a map for mustache rendering. + * Uses reflection to access fields from the object and its superclasses. + */ + private void copyObjectProperties(Object source, Map targetMap) { + if (source == null) return; + + Class clazz = source.getClass(); + while (clazz != null) { + for (Field field : clazz.getDeclaredFields()) { + try { + field.setAccessible(true); + Object value = field.get(source); + if (value != null) { + targetMap.put(field.getName(), value); + } + } catch (IllegalAccessException e) { + // Skip inaccessible fields + } + } + clazz = clazz.getSuperclass(); + } + } + + protected String readResourceTemplate(String templatePath) { + String fullPath = codegen.templateDir() + "/" + templatePath; + try (InputStream is = getClass().getClassLoader().getResourceAsStream(fullPath)) { + if (is == null) { + throw new RuntimeException("Template not found: " + fullPath); + } + return new String(is.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new RuntimeException("Cannot read template: " + fullPath, e); + } + } + + protected void writeFile(String filename, String content) throws IOException { + File file = new File(filename); + file.getParentFile().mkdirs(); + try (FileWriter writer = new FileWriter(file, StandardCharsets.UTF_8)) { + writer.write(content); + } + } + @Override public void addSupportVersion() { final List templateStrings = templates.get(VERSION_TEMPLATE); diff --git a/src/main/java/com/twilio/oai/template/CsharpApiActionTemplate.java b/src/main/java/com/twilio/oai/template/CsharpApiActionTemplate.java index b7b0f27c4..868fe795b 100644 --- a/src/main/java/com/twilio/oai/template/CsharpApiActionTemplate.java +++ b/src/main/java/com/twilio/oai/template/CsharpApiActionTemplate.java @@ -1,5 +1,6 @@ package com.twilio.oai.template; +import com.twilio.oai.java.cache.ResourceCacheContext; import org.openapitools.codegen.CodegenConfig; import java.util.Arrays; @@ -17,9 +18,16 @@ public CsharpApiActionTemplate(CodegenConfig defaultCodegen) { @Override public Map> mapping() { - return Map.of(TEMPLATE_TYPE_RESOURCE, - Arrays.asList(TEMPLATE_TYPE_RESOURCE + ".mustache", "Resource.cs"), - TEMPLATE_TYPE_OPTIONS, - Arrays.asList(TEMPLATE_TYPE_OPTIONS + ".mustache", "Options.cs")); + if (ResourceCacheContext.get().isV1()) { + return Map.of(TEMPLATE_TYPE_RESOURCE, + Arrays.asList(TEMPLATE_TYPE_RESOURCE + "_standard.mustache", "Resource.cs"), + TEMPLATE_TYPE_OPTIONS, + Arrays.asList(TEMPLATE_TYPE_OPTIONS + ".mustache", "Options.cs")); + } else { + return Map.of(TEMPLATE_TYPE_RESOURCE, + Arrays.asList(TEMPLATE_TYPE_RESOURCE + ".mustache", "Resource.cs"), + TEMPLATE_TYPE_OPTIONS, + Arrays.asList(TEMPLATE_TYPE_OPTIONS + ".mustache", "Options.cs")); + } } } diff --git a/src/main/java/com/twilio/oai/template/IApiActionTemplate.java b/src/main/java/com/twilio/oai/template/IApiActionTemplate.java index c9a3d4f3a..c42f12149 100644 --- a/src/main/java/com/twilio/oai/template/IApiActionTemplate.java +++ b/src/main/java/com/twilio/oai/template/IApiActionTemplate.java @@ -1,7 +1,15 @@ package com.twilio.oai.template; +import java.util.Map; + public interface IApiActionTemplate { void clean(); void add(String template); void addSupportVersion(); + + // Method for registering dynamic templates that generate multiple files from apiResource + void addDynamicTemplates(String templateType, Object apiResource); + + // Method to generate the dynamic files + void generateDynamicFiles(Map baseContext, String outputDir); } diff --git a/src/main/java/com/twilio/oai/template/PhpApiActionTemplate.java b/src/main/java/com/twilio/oai/template/PhpApiActionTemplate.java index d5b99fc73..173bac738 100644 --- a/src/main/java/com/twilio/oai/template/PhpApiActionTemplate.java +++ b/src/main/java/com/twilio/oai/template/PhpApiActionTemplate.java @@ -1,6 +1,7 @@ package com.twilio.oai.template; import java.util.Arrays; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -13,6 +14,8 @@ public class PhpApiActionTemplate extends AbstractApiActionTemplate { public static final String TEMPLATE_TYPE_INSTANCE = "instance"; public static final String TEMPLATE_TYPE_MODELS = "models"; public static final String TEMPLATE_TYPE_PAGE = "page"; + // New template type for individual instance classes (one file per response model) + public static final String TEMPLATE_TYPE_INSTANCE_CLASS = "instanceClass"; public PhpApiActionTemplate(final CodegenConfig defaultCodegen) { super(defaultCodegen); @@ -20,19 +23,16 @@ public PhpApiActionTemplate(final CodegenConfig defaultCodegen) { @Override protected Map> mapping() { - return Map.of(TEMPLATE_TYPE_LIST, - Arrays.asList(TEMPLATE_TYPE_LIST + ".mustache", "List.php"), - TEMPLATE_TYPE_CONTEXT, - Arrays.asList(TEMPLATE_TYPE_CONTEXT + ".mustache", "Context.php"), - TEMPLATE_TYPE_INSTANCE, - Arrays.asList(TEMPLATE_TYPE_INSTANCE + ".mustache", "Instance.php"), - TEMPLATE_TYPE_OPTIONS, - Arrays.asList(TEMPLATE_TYPE_OPTIONS + ".mustache", "Options.php"), - TEMPLATE_TYPE_MODELS, - Arrays.asList(TEMPLATE_TYPE_MODELS + ".mustache", "Models.php"), - TEMPLATE_TYPE_PAGE, - Arrays.asList(TEMPLATE_TYPE_PAGE + ".mustache", "Page.php"), - VERSION_TEMPLATE, - Arrays.asList(VERSION_TEMPLATE + ".mustache", ".php")); + Map> map = new HashMap<>(); + map.put(TEMPLATE_TYPE_LIST, Arrays.asList(TEMPLATE_TYPE_LIST + ".mustache", "List.php")); + map.put(TEMPLATE_TYPE_CONTEXT, Arrays.asList(TEMPLATE_TYPE_CONTEXT + ".mustache", "Context.php")); + map.put(TEMPLATE_TYPE_INSTANCE, Arrays.asList(TEMPLATE_TYPE_INSTANCE + ".mustache", "Instance.php")); + map.put(TEMPLATE_TYPE_OPTIONS, Arrays.asList(TEMPLATE_TYPE_OPTIONS + ".mustache", "Options.php")); + map.put(TEMPLATE_TYPE_MODELS, Arrays.asList(TEMPLATE_TYPE_MODELS + ".mustache", "Models.php")); + map.put(TEMPLATE_TYPE_PAGE, Arrays.asList(TEMPLATE_TYPE_PAGE + ".mustache", "Page.php")); + map.put(VERSION_TEMPLATE, Arrays.asList(VERSION_TEMPLATE + ".mustache", ".php")); + // Dynamic template for generating individual instance class files + map.put(TEMPLATE_TYPE_INSTANCE_CLASS, Arrays.asList("instanceClass.mustache", "Instance.php")); + return map; } } diff --git a/src/main/resources/twilio-csharp/Resource_standard.mustache b/src/main/resources/twilio-csharp/Resource_standard.mustache new file mode 100644 index 000000000..748d23732 --- /dev/null +++ b/src/main/resources/twilio-csharp/Resource_standard.mustache @@ -0,0 +1,32 @@ +{{>LicenseInfo}} + +{{#resources}} +{{>ResourceUsings}} + +namespace Twilio.Rest.{{domainPackage}}.{{apiVersionClass}}{{namespaceSubPart}} +{ + {{>standard/Response}} + public class {{apiName}}{{resourceConstant}} : {{resourceConstant}} + { + {{>models}} + {{>resource/Enum}} + {{#apiOperations}} + {{#vendorExtensions.x-is-create-operation}} + {{>resource/CreateResource}} + {{/vendorExtensions.x-is-create-operation}} + {{#vendorExtensions.x-is-delete-operation}} + {{>resource/DeleteResource}} + {{/vendorExtensions.x-is-delete-operation}} + {{#vendorExtensions.x-is-fetch-operation}} + {{>resource/FetchResource}} + {{/vendorExtensions.x-is-fetch-operation}} + {{#vendorExtensions.x-is-read-operation}} + {{>resource/ReadResource}} + {{/vendorExtensions.x-is-read-operation}} + {{#vendorExtensions.x-is-update-operation}} + {{>resource/UpdateResource}} + {{/vendorExtensions.x-is-update-operation}} + {{/apiOperations}} + } +} +{{/resources}} \ No newline at end of file diff --git a/src/main/resources/twilio-csharp/options/CreateOptions.mustache b/src/main/resources/twilio-csharp/options/CreateOptions.mustache index 953df3bb4..004981e71 100644 --- a/src/main/resources/twilio-csharp/options/CreateOptions.mustache +++ b/src/main/resources/twilio-csharp/options/CreateOptions.mustache @@ -1,6 +1,6 @@ {{>Summary}} - public class Create{{apiName}}Options : IOptions<{{apiName}}{{resourceConstant}}> + public class Create{{apiName}}Options : IOptions<{{apiName}}{{#isApiV1}}Create{{/isApiV1}}{{resourceConstant}}> { {{>options/Params}} {{#vendorExtensions.x-required-param-exists}} diff --git a/src/main/resources/twilio-csharp/options/FetchOptions.mustache b/src/main/resources/twilio-csharp/options/FetchOptions.mustache index 7b9034ef4..9d717a84c 100644 --- a/src/main/resources/twilio-csharp/options/FetchOptions.mustache +++ b/src/main/resources/twilio-csharp/options/FetchOptions.mustache @@ -1,5 +1,5 @@ {{>Summary}} - public class Fetch{{apiName}}Options : IOptions<{{apiName}}{{resourceConstant}}> + public class Fetch{{apiName}}Options : IOptions<{{apiName}}{{#isApiV1}}Fetch{{/isApiV1}}{{resourceConstant}}> { {{>options/Params}} diff --git a/src/main/resources/twilio-csharp/options/ReadOptions.mustache b/src/main/resources/twilio-csharp/options/ReadOptions.mustache index 06f74cf8b..c1a80f80b 100644 --- a/src/main/resources/twilio-csharp/options/ReadOptions.mustache +++ b/src/main/resources/twilio-csharp/options/ReadOptions.mustache @@ -1,5 +1,5 @@ {{>Summary}} - public class Read{{apiName}}Options : ReadOptions<{{apiName}}{{resourceConstant}}> + public class Read{{apiName}}Options : ReadOptions<{{apiName}}{{#isApiV1}}Read{{/isApiV1}}{{resourceConstant}}> { {{>options/Params}} diff --git a/src/main/resources/twilio-csharp/options/UpdateOptions.mustache b/src/main/resources/twilio-csharp/options/UpdateOptions.mustache index a2060d929..a6e210c6f 100644 --- a/src/main/resources/twilio-csharp/options/UpdateOptions.mustache +++ b/src/main/resources/twilio-csharp/options/UpdateOptions.mustache @@ -1,5 +1,5 @@ {{>Summary}} - public class Update{{apiName}}Options : IOptions<{{apiName}}{{resourceConstant}}> + public class Update{{apiName}}Options : IOptions<{{apiName}}{{#isApiV1}}Update{{/isApiV1}}{{resourceConstant}}> { {{>options/Params}} diff --git a/src/main/resources/twilio-csharp/resource/CreateResource.mustache b/src/main/resources/twilio-csharp/resource/CreateResource.mustache index 4b6fb8618..c99e0168f 100644 --- a/src/main/resources/twilio-csharp/resource/CreateResource.mustache +++ b/src/main/resources/twilio-csharp/resource/CreateResource.mustache @@ -21,11 +21,11 @@ /// Create {{apiName}} parameters /// Client to make requests to Twilio {{>resource/ReturnComments}} - public static {{apiName}}{{resourceConstant}} Create(Create{{apiName}}Options options, ITwilioRestClient client = null) + public static {{apiName}}{{#isApiV1}}Create{{/isApiV1}}{{resourceConstant}} Create(Create{{apiName}}Options options, ITwilioRestClient client = null) { client = client ?? TwilioClient.{{restClientMethodName}}(); var response = client.Request(BuildCreateRequest(options, client)); - return FromJson(response.Content); + return {{#isApiV1}}{{apiName}}Create{{resourceConstant}}.{{/isApiV1}}FromJson(response.Content); } #if !NET35 @@ -33,17 +33,17 @@ /// Create {{apiName}} parameters /// Client to make requests to Twilio {{>resource/ReturnCommentsAsync}} - public static async System.Threading.Tasks.Task<{{apiName}}{{resourceConstant}}> CreateAsync(Create{{apiName}}Options options, ITwilioRestClient client = null) + public static async System.Threading.Tasks.Task<{{apiName}}{{#isApiV1}}Create{{/isApiV1}}{{resourceConstant}}> CreateAsync(Create{{apiName}}Options options, ITwilioRestClient client = null) { client = client ?? TwilioClient.{{restClientMethodName}}(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); - return FromJson(response.Content); + return {{#isApiV1}}{{apiName}}Create{{resourceConstant}}.{{/isApiV1}}FromJson(response.Content); } #endif {{>Summary}}{{>resource/MethodsComments}} {{>resource/ReturnComments}} - public static {{apiName}}{{resourceConstant}} Create({{#vendorExtensions.x-request-body-param}} + public static {{apiName}}{{#isApiV1}}Create{{/isApiV1}}{{resourceConstant}} Create({{#vendorExtensions.x-request-body-param}} {{{dataType}}} {{#lambda.camelcase}}{{paramName}}{{/lambda.camelcase}}{{^required}} = null{{/required}},{{/vendorExtensions.x-request-body-param}} ITwilioRestClient client = null) { @@ -54,7 +54,7 @@ #if !NET35 {{>Summary}}{{>resource/MethodsComments}} {{>resource/ReturnCommentsAsync}} - public static async System.Threading.Tasks.Task<{{apiName}}{{resourceConstant}}> CreateAsync({{#vendorExtensions.x-request-body-param}} + public static async System.Threading.Tasks.Task<{{apiName}}{{#isApiV1}}Create{{/isApiV1}}{{resourceConstant}}> CreateAsync({{#vendorExtensions.x-request-body-param}} {{{dataType}}} {{#lambda.camelcase}}{{paramName}}{{/lambda.camelcase}}{{^required}} = null{{/required}},{{/vendorExtensions.x-request-body-param}} ITwilioRestClient client = null) { diff --git a/src/main/resources/twilio-csharp/resource/FetchResource.mustache b/src/main/resources/twilio-csharp/resource/FetchResource.mustache index aebb634c5..eb74297ed 100644 --- a/src/main/resources/twilio-csharp/resource/FetchResource.mustache +++ b/src/main/resources/twilio-csharp/resource/FetchResource.mustache @@ -15,11 +15,11 @@ /// Fetch {{apiName}} parameters /// Client to make requests to Twilio {{>resource/ReturnComments}} - public static {{apiName}}Resource Fetch(Fetch{{apiName}}Options options, ITwilioRestClient client = null) + public static {{apiName}}{{#isApiV1}}Fetch{{/isApiV1}}Resource Fetch(Fetch{{apiName}}Options options, ITwilioRestClient client = null) { client = client ?? TwilioClient.{{restClientMethodName}}(); var response = client.Request(BuildFetchRequest(options, client)); - return FromJson(response.Content); + return {{#isApiV1}}{{apiName}}Fetch{{resourceConstant}}.{{/isApiV1}}FromJson(response.Content); } #if !NET35 @@ -27,16 +27,16 @@ /// Fetch {{apiName}} parameters /// Client to make requests to Twilio {{>resource/ReturnCommentsAsync}} - public static async System.Threading.Tasks.Task<{{apiName}}Resource> FetchAsync(Fetch{{apiName}}Options options, ITwilioRestClient client = null) + public static async System.Threading.Tasks.Task<{{apiName}}{{#isApiV1}}Fetch{{/isApiV1}}Resource> FetchAsync(Fetch{{apiName}}Options options, ITwilioRestClient client = null) { client = client ?? TwilioClient.{{restClientMethodName}}(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); - return FromJson(response.Content); + return {{#isApiV1}}{{apiName}}Fetch{{resourceConstant}}.{{/isApiV1}}FromJson(response.Content); } #endif {{>Summary}}{{>resource/MethodsComments}} {{>resource/ReturnComments}} - public static {{apiName}}{{resourceConstant}} Fetch({{#vendorExtensions.x-request-body-param}} + public static {{apiName}}{{#isApiV1}}Fetch{{/isApiV1}}{{resourceConstant}} Fetch({{#vendorExtensions.x-request-body-param}} {{{dataType}}} {{#lambda.camelcase}}{{paramName}}{{/lambda.camelcase}}{{^required}} = null{{/required}}, {{/vendorExtensions.x-request-body-param}} ITwilioRestClient client = null) { @@ -47,7 +47,7 @@ #if !NET35 {{>Summary}}{{>resource/MethodsComments}} {{>resource/ReturnCommentsAsync}} - public static async System.Threading.Tasks.Task<{{apiName}}{{resourceConstant}}> FetchAsync({{#vendorExtensions.x-request-body-param}}{{{dataType}}} {{#lambda.camelcase}}{{paramName}}{{/lambda.camelcase}}{{^required}} = null{{/required}}, {{/vendorExtensions.x-request-body-param}}ITwilioRestClient client = null) + public static async System.Threading.Tasks.Task<{{apiName}}{{#isApiV1}}Fetch{{/isApiV1}}{{resourceConstant}}> FetchAsync({{#vendorExtensions.x-request-body-param}}{{{dataType}}} {{#lambda.camelcase}}{{paramName}}{{/lambda.camelcase}}{{^required}} = null{{/required}}, {{/vendorExtensions.x-request-body-param}}ITwilioRestClient client = null) { var options = new Fetch{{apiName}}Options({{#requiredParams}}{{#lambda.camelcase}}{{paramName}}{{/lambda.camelcase}}{{^-last}}, {{/-last}}{{/requiredParams}}){ {{#vendorExtensions.x-request-body-param}}{{^required}}{{paramName}} = {{#lambda.camelcase}}{{paramName}}{{/lambda.camelcase}}{{^-last}},{{/-last}}{{/required}}{{/vendorExtensions.x-request-body-param}} }; return await FetchAsync(options, client); diff --git a/src/main/resources/twilio-csharp/resource/ReadResource.mustache b/src/main/resources/twilio-csharp/resource/ReadResource.mustache index eca96b6a3..caf694bae 100644 --- a/src/main/resources/twilio-csharp/resource/ReadResource.mustache +++ b/src/main/resources/twilio-csharp/resource/ReadResource.mustache @@ -14,12 +14,12 @@ /// Read {{apiName}} parameters /// Client to make requests to Twilio {{>resource/ReturnComments}} - public static ResourceSet<{{apiName}}{{resourceConstant}}> Read(Read{{apiName}}Options options, ITwilioRestClient client = null) + public static ResourceSet<{{apiName}}{{#isApiV1}}Read{{/isApiV1}}{{resourceConstant}}> Read(Read{{apiName}}Options options, ITwilioRestClient client = null) { client = client ?? TwilioClient.{{restClientMethodName}}(); var response = client.Request(BuildReadRequest(options, client)); - var page = Page<{{apiName}}{{resourceConstant}}>.FromJson("{{recordKey}}", response.Content); - return new ResourceSet<{{apiName}}{{resourceConstant}}>(page, options, client); + var page = Page<{{apiName}}{{#isApiV1}}Read{{/isApiV1}}{{resourceConstant}}>.FromJson("{{recordKey}}", response.Content); + return new ResourceSet<{{apiName}}{{#isApiV1}}Read{{/isApiV1}}{{resourceConstant}}>(page, options, client); } #if !NET35 @@ -27,18 +27,18 @@ /// Read {{apiName}} parameters /// Client to make requests to Twilio {{>resource/ReturnCommentsAsync}} - public static async System.Threading.Tasks.Task> ReadAsync(Read{{apiName}}Options options, ITwilioRestClient client = null) + public static async System.Threading.Tasks.Task> ReadAsync(Read{{apiName}}Options options, ITwilioRestClient client = null) { client = client ?? TwilioClient.{{restClientMethodName}}(); var response = await client.RequestAsync(BuildReadRequest(options, client)); - var page = Page<{{apiName}}{{resourceConstant}}>.FromJson("{{recordKey}}", response.Content); - return new ResourceSet<{{apiName}}{{resourceConstant}}>(page, options, client); + var page = Page<{{apiName}}{{#isApiV1}}Read{{/isApiV1}}{{resourceConstant}}>.FromJson("{{recordKey}}", response.Content); + return new ResourceSet<{{apiName}}{{#isApiV1}}Read{{/isApiV1}}{{resourceConstant}}>(page, options, client); } #endif {{>Summary}}{{>resource/MethodsComments}} {{>resource/ReturnComments}} - public static ResourceSet<{{apiName}}{{resourceConstant}}> Read({{#vendorExtensions.x-request-body-param}} + public static ResourceSet<{{apiName}}{{#isApiV1}}Read{{/isApiV1}}{{resourceConstant}}> Read({{#vendorExtensions.x-request-body-param}} {{{dataType}}} {{#lambda.camelcase}}{{paramName}}{{/lambda.camelcase}}{{^required}} = null{{/required}},{{/vendorExtensions.x-request-body-param}} long? limit = null, ITwilioRestClient client = null) @@ -50,7 +50,7 @@ #if !NET35 {{>Summary}}{{>resource/MethodsComments}} {{>resource/ReturnCommentsAsync}} - public static async System.Threading.Tasks.Task> ReadAsync({{#vendorExtensions.x-request-body-param}} + public static async System.Threading.Tasks.Task> ReadAsync({{#vendorExtensions.x-request-body-param}} {{{dataType}}} {{#lambda.camelcase}}{{paramName}}{{/lambda.camelcase}}{{^required}} = null{{/required}},{{/vendorExtensions.x-request-body-param}} long? limit = null, ITwilioRestClient client = null) diff --git a/src/main/resources/twilio-csharp/resource/UpdateResource.mustache b/src/main/resources/twilio-csharp/resource/UpdateResource.mustache index 1584db2c0..1c28b22d1 100644 --- a/src/main/resources/twilio-csharp/resource/UpdateResource.mustache +++ b/src/main/resources/twilio-csharp/resource/UpdateResource.mustache @@ -21,11 +21,11 @@ /// Update {{apiName}} parameters /// Client to make requests to Twilio {{>resource/ReturnComments}} - public static {{apiName}}{{resourceConstant}} Update(Update{{apiName}}Options options, ITwilioRestClient client = null) + public static {{apiName}}{{#isApiV1}}Update{{/isApiV1}}{{resourceConstant}} Update(Update{{apiName}}Options options, ITwilioRestClient client = null) { client = client ?? TwilioClient.{{restClientMethodName}}(); var response = client.Request(BuildUpdateRequest(options, client)); - return FromJson(response.Content); + return {{#isApiV1}}{{apiName}}Update{{resourceConstant}}.{{/isApiV1}}FromJson(response.Content); } {{>Summary}} @@ -33,18 +33,18 @@ /// Client to make requests to Twilio {{>resource/ReturnCommentsAsync}} #if !NET35 - public static async System.Threading.Tasks.Task<{{apiName}}{{resourceConstant}}> UpdateAsync(Update{{apiName}}Options options, + public static async System.Threading.Tasks.Task<{{apiName}}{{#isApiV1}}Update{{/isApiV1}}{{resourceConstant}}> UpdateAsync(Update{{apiName}}Options options, ITwilioRestClient client = null) { client = client ?? TwilioClient.{{restClientMethodName}}(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); - return FromJson(response.Content); + return {{#isApiV1}}{{apiName}}Update{{resourceConstant}}.{{/isApiV1}}FromJson(response.Content); } #endif {{>Summary}}{{>resource/MethodsComments}} {{>resource/ReturnComments}} - public static {{apiName}}{{resourceConstant}} Update({{#vendorExtensions.x-request-body-param}} + public static {{apiName}}{{#isApiV1}}Update{{/isApiV1}}{{resourceConstant}} Update({{#vendorExtensions.x-request-body-param}} {{{dataType}}} {{#lambda.camelcase}}{{paramName}}{{/lambda.camelcase}}{{^required}} = null{{/required}},{{/vendorExtensions.x-request-body-param}} ITwilioRestClient client = null) { @@ -55,7 +55,7 @@ #if !NET35 {{>Summary}}{{>resource/MethodsComments}} {{>resource/ReturnCommentsAsync}} - public static async System.Threading.Tasks.Task<{{apiName}}{{resourceConstant}}> UpdateAsync({{#vendorExtensions.x-request-body-param}} + public static async System.Threading.Tasks.Task<{{apiName}}{{#isApiV1}}Update{{/isApiV1}}{{resourceConstant}}> UpdateAsync({{#vendorExtensions.x-request-body-param}} {{{dataType}}} {{#lambda.camelcase}}{{paramName}}{{/lambda.camelcase}}{{^required}} = null{{/required}},{{/vendorExtensions.x-request-body-param}} ITwilioRestClient client = null) { diff --git a/src/main/resources/twilio-csharp/standard/CreateResponse.mustache b/src/main/resources/twilio-csharp/standard/CreateResponse.mustache new file mode 100644 index 000000000..97f3a032d --- /dev/null +++ b/src/main/resources/twilio-csharp/standard/CreateResponse.mustache @@ -0,0 +1,46 @@ + +public class {{apiName}}Create{{resourceConstant}} : {{resourceConstant}} +{ +{{#createResponseModels}} + {{#isEnum}} + {{#description}}/// {{{description}}} {{/description}} + [JsonProperty("{{baseName}}")] + {{^required}} + public {{{dataType}}} {{nameInCamelCase}} { get; private set; } + {{/required}} + {{#required}} + public {{{dataType}}} {{nameInCamelCase}} { get; } + {{/required}} + {{/isEnum}} + {{^isEnum}} + {{#description}}/// {{{description}}} {{/description}}{{^description}}/// The {{baseName}} {{/description}} + [JsonProperty("{{baseName}}")] + {{#vendorExtensions.x-jsonConverter}} + [JsonConverter(typeof({{vendorExtensions.x-jsonConverter}}))] + {{/vendorExtensions.x-jsonConverter}} + {{^required}} + public {{{dataType}}} {{nameInCamelCase}} { get; private set; } + {{/required}} + {{#required}} + public {{{dataType}}} {{nameInCamelCase}} { get; } + {{/required}} + {{/isEnum}} + +{{/createResponseModels}} + public static {{apiName}}Create{{resourceConstant}} FromJson(string json) { + try { + return JsonConvert.DeserializeObject<{{apiName}}Create{{resourceConstant}}>(json); + } + catch (JsonException e) { + throw new ApiException(e.Message, e); + } + } + public static string ToJson(object model) { + try { + return JsonConvert.SerializeObject(model); + } + catch (JsonException e) { + throw new ApiException(e.Message, e); + } + } +} \ No newline at end of file diff --git a/src/main/resources/twilio-csharp/standard/FetchResponse.mustache b/src/main/resources/twilio-csharp/standard/FetchResponse.mustache new file mode 100644 index 000000000..409a9c7de --- /dev/null +++ b/src/main/resources/twilio-csharp/standard/FetchResponse.mustache @@ -0,0 +1,46 @@ +public class {{apiName}}Fetch{{resourceConstant}} : {{resourceConstant}} +{ +{{#fetchResponseModels}} + {{#isEnum}} + {{#description}}/// {{{description}}} {{/description}} + [JsonProperty("{{baseName}}")] + {{^required}} + public {{{dataType}}} {{nameInCamelCase}} { get; private set; } + {{/required}} + {{#required}} + public {{{dataType}}} {{nameInCamelCase}} { get; } + {{/required}} + {{/isEnum}} + {{^isEnum}} + {{#description}}/// {{{description}}} {{/description}}{{^description}}/// The {{baseName}} {{/description}} + [JsonProperty("{{baseName}}")] + {{#vendorExtensions.x-jsonConverter}} + [JsonConverter(typeof({{vendorExtensions.x-jsonConverter}}))] + {{/vendorExtensions.x-jsonConverter}} + {{^required}} + public {{{dataType}}} {{nameInCamelCase}} { get; private set; } + {{/required}} + {{#required}} + public {{{dataType}}} {{nameInCamelCase}} { get; } + {{/required}} + {{/isEnum}} + +{{/fetchResponseModels}} + + public static {{apiName}}Fetch{{resourceConstant}} FromJson(string json) { + try { + return JsonConvert.DeserializeObject<{{apiName}}Fetch{{resourceConstant}}>(json); + } + catch (JsonException e) { + throw new ApiException(e.Message, e); + } + } + public static string ToJson(object model) { + try { + return JsonConvert.SerializeObject(model); + } + catch (JsonException e) { + throw new ApiException(e.Message, e); + } + } +} \ No newline at end of file diff --git a/src/main/resources/twilio-csharp/standard/PatchResponse.mustache b/src/main/resources/twilio-csharp/standard/PatchResponse.mustache new file mode 100644 index 000000000..b4f63738b --- /dev/null +++ b/src/main/resources/twilio-csharp/standard/PatchResponse.mustache @@ -0,0 +1,46 @@ +public class {{apiName}}Patch{{resourceConstant}} : {{resourceConstant}} +{ +{{#patchResponseModels}} + {{#isEnum}} + {{#description}}/// {{{description}}} {{/description}} + [JsonProperty("{{baseName}}")] + {{^required}} + public {{{dataType}}} {{nameInCamelCase}} { get; private set; } + {{/required}} + {{#required}} + public {{{dataType}}} {{nameInCamelCase}} { get; } + {{/required}} + {{/isEnum}} + {{^isEnum}} + {{#description}}/// {{{description}}} {{/description}}{{^description}}/// The {{baseName}} {{/description}} + [JsonProperty("{{baseName}}")] + {{#vendorExtensions.x-jsonConverter}} + [JsonConverter(typeof({{vendorExtensions.x-jsonConverter}}))] + {{/vendorExtensions.x-jsonConverter}} + {{^required}} + public {{{dataType}}} {{nameInCamelCase}} { get; private set; } + {{/required}} + {{#required}} + public {{{dataType}}} {{nameInCamelCase}} { get; } + {{/required}} + {{/isEnum}} + +{{/patchResponseModels}} + + public static {{apiName}}Patch{{resourceConstant}} FromJson(string json) { + try { + return JsonConvert.DeserializeObject<{{apiName}}Patch{{resourceConstant}}>(json); + } + catch (JsonException e) { + throw new ApiException(e.Message, e); + } + } + public static string ToJson(object model) { + try { + return JsonConvert.SerializeObject(model); + } + catch (JsonException e) { + throw new ApiException(e.Message, e); + } + } +} \ No newline at end of file diff --git a/src/main/resources/twilio-csharp/standard/ReadResponse.mustache b/src/main/resources/twilio-csharp/standard/ReadResponse.mustache new file mode 100644 index 000000000..ca032f268 --- /dev/null +++ b/src/main/resources/twilio-csharp/standard/ReadResponse.mustache @@ -0,0 +1,45 @@ +public class {{apiName}}Read{{resourceConstant}} : {{resourceConstant}} +{ +{{#listResponseModels}} + {{#isEnum}} + {{#description}}/// {{{description}}} {{/description}} + [JsonProperty("{{baseName}}")] + {{^required}} + public {{{dataType}}} {{nameInCamelCase}} { get; private set; } + {{/required}} + {{#required}} + public {{{dataType}}} {{nameInCamelCase}} { get; } + {{/required}} + {{/isEnum}} + {{^isEnum}} + {{#description}}/// {{{description}}} {{/description}}{{^description}}/// The {{baseName}} {{/description}} + [JsonProperty("{{baseName}}")] + {{#vendorExtensions.x-jsonConverter}} + [JsonConverter(typeof({{vendorExtensions.x-jsonConverter}}))] + {{/vendorExtensions.x-jsonConverter}} + {{^required}} + public {{{dataType}}} {{nameInCamelCase}} { get; private set; } + {{/required}} + {{#required}} + public {{{dataType}}} {{nameInCamelCase}} { get; } + {{/required}} + {{/isEnum}} + +{{/listResponseModels}} + public static {{apiName}}Read{{resourceConstant}} FromJson(string json) { + try { + return JsonConvert.DeserializeObject<{{apiName}}Read{{resourceConstant}}>(json); + } + catch (JsonException e) { + throw new ApiException(e.Message, e); + } + } + public static string ToJson(object model) { + try { + return JsonConvert.SerializeObject(model); + } + catch (JsonException e) { + throw new ApiException(e.Message, e); + } + } +} \ No newline at end of file diff --git a/src/main/resources/twilio-csharp/standard/Response.mustache b/src/main/resources/twilio-csharp/standard/Response.mustache new file mode 100644 index 000000000..58e5f8099 --- /dev/null +++ b/src/main/resources/twilio-csharp/standard/Response.mustache @@ -0,0 +1,14 @@ +{{#apiOperations}} + {{#vendorExtensions.x-is-create-operation}} + {{>standard/CreateResponse}} + {{/vendorExtensions.x-is-create-operation}} + {{#vendorExtensions.x-is-fetch-operation}} + {{>standard/FetchResponse}} + {{/vendorExtensions.x-is-fetch-operation}} + {{#vendorExtensions.x-is-read-operation}} + {{>standard/ReadResponse}} + {{/vendorExtensions.x-is-read-operation}} + {{#vendorExtensions.x-is-update-operation}} + {{>standard/UpdateResponse}} + {{/vendorExtensions.x-is-update-operation}} +{{/apiOperations}} \ No newline at end of file diff --git a/src/main/resources/twilio-csharp/standard/UpdateResponse.mustache b/src/main/resources/twilio-csharp/standard/UpdateResponse.mustache new file mode 100644 index 000000000..ace23e43b --- /dev/null +++ b/src/main/resources/twilio-csharp/standard/UpdateResponse.mustache @@ -0,0 +1,46 @@ +public class {{apiName}}Update{{resourceConstant}} : {{resourceConstant}} +{ +{{#updateResponseModels}} + {{#isEnum}} + {{#description}}/// {{{description}}} {{/description}} + [JsonProperty("{{baseName}}")] + {{^required}} + public {{{dataType}}} {{nameInCamelCase}} { get; private set; } + {{/required}} + {{#required}} + public {{{dataType}}} {{nameInCamelCase}} { get; } + {{/required}} + {{/isEnum}} + {{^isEnum}} + {{#description}}/// {{{description}}} {{/description}}{{^description}}/// The {{baseName}} {{/description}} + [JsonProperty("{{baseName}}")] + {{#vendorExtensions.x-jsonConverter}} + [JsonConverter(typeof({{vendorExtensions.x-jsonConverter}}))] + {{/vendorExtensions.x-jsonConverter}} + {{^required}} + public {{{dataType}}} {{nameInCamelCase}} { get; private set; } + {{/required}} + {{#required}} + public {{{dataType}}} {{nameInCamelCase}} { get; } + {{/required}} + {{/isEnum}} + +{{/updateResponseModels}} + + public static {{apiName}}Update{{resourceConstant}} FromJson(string json) { + try { + return JsonConvert.DeserializeObject<{{apiName}}Update{{resourceConstant}}>(json); + } + catch (JsonException e) { + throw new ApiException(e.Message, e); + } + } + public static string ToJson(object model) { + try { + return JsonConvert.SerializeObject(model); + } + catch (JsonException e) { + throw new ApiException(e.Message, e); + } + } +} \ No newline at end of file diff --git a/src/main/resources/twilio-go/api.mustache b/src/main/resources/twilio-go/api.mustache index b2af4e03d..f76c3b6c6 100644 --- a/src/main/resources/twilio-go/api.mustache +++ b/src/main/resources/twilio-go/api.mustache @@ -80,16 +80,18 @@ func (c *ApiService) {{{nickname}}}({{#allParams}}{{#required}}{{paramName}} {{{ {{/vendorExtensions.x-is-read-operation}} {{#vendorExtensions.x-is-read-operation}} // Retrieve a single page of {{{vendorExtensions.x-domain-name}}} records from the API. Request is executed immediately. -func (c *ApiService) Page{{{vendorExtensions.x-domain-name}}}({{#allParams}}{{#required}}{{paramName}} {{{dataType}}}{{^last}}, {{/last}}{{/required}}{{/allParams}}params *{{{nickname}}}Params, pageToken, pageNumber string) (*{{{returnContainer}}}, error) { +func (c *ApiService) Page{{{vendorExtensions.x-domain-name}}}({{#allParams}}{{#required}}{{paramName}} {{{dataType}}}{{^last}}, {{/last}}{{/required}}{{/allParams}}params *{{{nickname}}}Params{{#vendorExtensions.isApiV1}}, pageToken string{{/vendorExtensions.isApiV1}}{{^vendorExtensions.isApiV1}}, pageToken, pageNumber string{{/vendorExtensions.isApiV1}}) (*{{{returnContainer}}}, error) { path := "{{{path}}}" {{>partial_serialization}} if pageToken != "" { data.Set("PageToken", pageToken) } + {{^vendorExtensions.isApiV1}} if pageNumber != "" { data.Set("Page", pageNumber) } + {{/vendorExtensions.isApiV1}} resp, err := c.requestHandler.Get(c.baseURL+path, data, headers) if err != nil { @@ -132,7 +134,7 @@ func (c *ApiService) Stream{{{vendorExtensions.x-domain-name}}}({{#allParams}}{{ recordChannel := make(chan {{{returnBaseType}}}, 1) errorChannel := make(chan error, 1) - response, err := c.Page{{{vendorExtensions.x-domain-name}}}({{#allParams}}{{#required}}{{paramName}}{{^last}}, {{/last}}{{/required}}{{/allParams}}params, "", "") + response, err := c.Page{{{vendorExtensions.x-domain-name}}}({{#allParams}}{{#required}}{{paramName}}{{^last}}, {{/last}}{{/required}}{{/allParams}}params, ""{{^vendorExtensions.isApiV1}}, ""{{/vendorExtensions.isApiV1}}) if err != nil { errorChannel <- err close(recordChannel) @@ -160,7 +162,7 @@ func (c *ApiService) stream{{{vendorExtensions.x-domain-name}}}(response *{{{ret } } - record, err := client.GetNext(c.baseURL, response, c.getNext{{{returnContainer}}}) + record, err := client.GetNext(c.baseURL{{#vendorExtensions.isApiV1}}+"{{{path}}}"{{/vendorExtensions.isApiV1}}, response, c.getNext{{{returnContainer}}}) if err != nil { errorChannel <- err break diff --git a/src/main/resources/twilio-go/api_service.mustache b/src/main/resources/twilio-go/api_service.mustache index 2ff6d7e88..031587592 100644 --- a/src/main/resources/twilio-go/api_service.mustache +++ b/src/main/resources/twilio-go/api_service.mustache @@ -7,17 +7,27 @@ import ( type ApiService struct { baseURL string - requestHandler *twilio.RequestHandler + requestHandler *twilio.RequestHandler{{#isApiV1}} + apiVersion string{{/isApiV1}} } func (c *ApiService) RequestHandler() *twilio.RequestHandler { return c.requestHandler } +{{#isApiV1}} + +// ApiVersion returns the API Standards version for this service +func (c *ApiService) ApiVersion() string { + return c.apiVersion +} +{{/isApiV1}} func NewApiService(requestHandler *twilio.RequestHandler) *ApiService { - return &ApiService { + {{#isApiV1}}requestHandler.SetApiVersion("v1.0"){{/isApiV1}} + return &ApiService { requestHandler: requestHandler, - baseURL: "{{#hasServers}}{{#servers}}{{url}}{{/servers}}{{/hasServers}}", + baseURL: "{{#hasServers}}{{#servers}}{{url}}{{/servers}}{{/hasServers}}",{{#isApiV1}} + apiVersion: "v1.0",{{/isApiV1}} } } diff --git a/src/main/resources/twilio-java/reader.mustache b/src/main/resources/twilio-java/reader.mustache index 32f5f2f4b..c1cb0ea4e 100644 --- a/src/main/resources/twilio-java/reader.mustache +++ b/src/main/resources/twilio-java/reader.mustache @@ -2,7 +2,8 @@ {{#resources}} package com.twilio.rest.{{domainPackage}}.{{apiVersion}}{{namespaceSubPart}}; {{>common/imports}} -import com.twilio.base.Page; +import com.twilio.base.Page;{{#isApiV1}} +import com.twilio.base.TokenPaginationPage;{{/isApiV1}} import com.twilio.base.ResourceSet; {{#operations}} @@ -13,6 +14,7 @@ public class {{resourceName}}Reader extends Reader<{{resourceName}}> { {{>common/constructors}} {{>reader/setters}} {{>reader/operationMethod}} + {{>reader/paginationMethods}} {{! Query is mandatory for list operations }} {{>common/addQueryParams}} @@ -22,4 +24,4 @@ public class {{resourceName}}Reader extends Reader<{{resourceName}}> { } {{/vendorExtensions.x-list-operation}} {{/operations}} -{{/resources}} \ No newline at end of file +{{/resources}} diff --git a/src/main/resources/twilio-java/reader/operationMethod.mustache b/src/main/resources/twilio-java/reader/operationMethod.mustache index 7dea9b5d8..87bb9ccb3 100644 --- a/src/main/resources/twilio-java/reader/operationMethod.mustache +++ b/src/main/resources/twilio-java/reader/operationMethod.mustache @@ -1,6 +1,6 @@ -{{! +{{! resourceName: Api Name as identified by Directory Structure service -recordKey: +recordKey: httpMethod: http method associated in the current operation. domainName: example api, video, chat, etc. These can be found in Domains.java in twilio-java }} @@ -8,7 +8,7 @@ domainName: example api, video, chat, etc. These can be found in Domains.java in public ResourceSet<{{resourceName}}> read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - + public Page<{{resourceName}}> firstPage(final TwilioRestClient client) { {{>common/generateUri}} Request request = new Request( @@ -28,43 +28,3 @@ domainName: example api, video, chat, etc. These can be found in Domains.java in return pageForRequest(client, request); } - - private Page<{{resourceName}}> pageForRequest(final TwilioRestClient client, final Request request) { - Response response = client.request(request); - if (response == null) { - throw new ApiConnectionException("{{resourceName}} read failed: Unable to connect to server"); - } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { - RestException restException = RestException.fromJson( - response.getStream(), - client.getObjectMapper()); - - if (restException == null) { - throw new ApiException("Server Error, no content", response.getStatusCode()); - } - throw new ApiException(restException); - } {{! end of else if }} - - return Page.fromJson( - "{{recordKey}}", - response.getContent(), - {{resourceName}}.class, - client.getObjectMapper()); - } - - @Override - public Page<{{resourceName}}> previousPage(final Page<{{resourceName}}> page, final TwilioRestClient client ) { - Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString())); - return pageForRequest(client, request); - } - - @Override - public Page<{{resourceName}}> nextPage(final Page<{{resourceName}}> page, final TwilioRestClient client) { - Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString())); - return pageForRequest(client, request); - } - - @Override - public Page<{{resourceName}}> getPage(final String targetUrl, final TwilioRestClient client) { - Request request = new Request(HttpMethod.GET, targetUrl); - return pageForRequest(client, request); - } \ No newline at end of file diff --git a/src/main/resources/twilio-java/reader/paginationMethods.mustache b/src/main/resources/twilio-java/reader/paginationMethods.mustache index e69de29bb..b2580564e 100644 --- a/src/main/resources/twilio-java/reader/paginationMethods.mustache +++ b/src/main/resources/twilio-java/reader/paginationMethods.mustache @@ -0,0 +1,57 @@ +private Page<{{resourceName}}> pageForRequest(final TwilioRestClient client, final Request request) { + Response response = client.request(request); + if (response == null) { + throw new ApiConnectionException("{{resourceName}} read failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson( + response.getStream(), + client.getObjectMapper()); + + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } {{! end of else if }} + + return {{#isApiV1}}TokenPaginationPage{{/isApiV1}}{{^isApiV1}}Page{{/isApiV1}}.fromJson( + "{{recordKey}}", + response.getContent(), + {{resourceName}}.class, + client.getObjectMapper()); + } + + @Override + public Page<{{resourceName}}> previousPage(final Page<{{resourceName}}> page, final TwilioRestClient client ) { + {{#isApiV1}} + {{>common/generateUri}} + path = path + page.previousQueryString(); + Request request = new Request( + HttpMethod.{{httpMethod}}, + Domains.{{#lambda.uppercase}}{{domainName}}{{/lambda.uppercase}}.toString(), + path + ); + {{/isApiV1}} + {{^isApiV1}}Request request = new Request(HttpMethod.GET, page.getPreviousPageUrl(Domains.API.toString()));{{/isApiV1}} + return pageForRequest(client, request); + } + + @Override + public Page<{{resourceName}}> nextPage(final Page<{{resourceName}}> page, final TwilioRestClient client) { + {{#isApiV1}} + {{>common/generateUri}} + path = path + page.nextQueryString(); + Request request = new Request( + HttpMethod.{{httpMethod}}, + Domains.{{#lambda.uppercase}}{{domainName}}{{/lambda.uppercase}}.toString(), + path + ); + {{/isApiV1}} + {{^isApiV1}}Request request = new Request(HttpMethod.GET, page.getNextPageUrl(Domains.API.toString()));{{/isApiV1}} + return pageForRequest(client, request); + } + + @Override + public Page<{{resourceName}}> getPage(final String targetUrl, final TwilioRestClient client) { + Request request = new Request(HttpMethod.GET, targetUrl); + return pageForRequest(client, request); + } diff --git a/src/main/resources/twilio-php/context.mustache b/src/main/resources/twilio-php/context.mustache index 7b37fc329..c6a346449 100644 --- a/src/main/resources/twilio-php/context.mustache +++ b/src/main/resources/twilio-php/context.mustache @@ -49,7 +49,8 @@ class {{apiName}}Context extends InstanceContext Version $version{{#requiredPathParams}}, ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/requiredPathParams}} ) { - parent::__construct($version); + {{^isApiV1}}parent::__construct($version);{{/isApiV1}}{{#isApiV1}}$apiV1Version = new ApiV1Version($version->getDomain(), $version->version); + parent::__construct($apiV1Version);{{/isApiV1}} // Path Solution $this->solution = [{{#requiredPathParams}} @@ -63,8 +64,8 @@ class {{apiName}}Context extends InstanceContext } {{#apiOperations}} -{{#vendorExtensions.instanceOperation}}{{>method}} -{{>contextMethod}} +{{#vendorExtensions.instanceOperation}} +{{>helperMethod}} {{/vendorExtensions.instanceOperation}} {{/apiOperations}} diff --git a/src/main/resources/twilio-php/contextMethod.mustache b/src/main/resources/twilio-php/contextMethod.mustache index efae75c64..e3cf40d27 100644 --- a/src/main/resources/twilio-php/contextMethod.mustache +++ b/src/main/resources/twilio-php/contextMethod.mustache @@ -140,7 +140,7 @@ {{^vendorExtensions.x-is-delete-operation}} $payload = $this->version->{{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}('{{httpMethod}}', $this->uri{{#queryParams.0}}, $params{{/queryParams.0}}{{^queryParams}}, []{{/queryParams}}{{#formParams.0}}, $data{{/formParams.0}}{{^formParams}}{{#bodyParams.0}}, $data{{/bodyParams.0}}{{^bodyParams}}, []{{/bodyParams}}{{/formParams}}, $headers); - return new {{apiName}}Instance( + return new {{^isApiV1}}{{apiName}}{{/isApiV1}}{{#isApiV1}}{{returnBaseType}}{{/isApiV1}}Instance( $this->version, $payload{{#optionalParams}}{{#isPathParam}}, $this->solution['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}']{{/isPathParam}}{{/optionalParams}}{{#requiredParams}}{{#isPathParam}}, diff --git a/src/main/resources/twilio-php/helperMethod.mustache b/src/main/resources/twilio-php/helperMethod.mustache new file mode 100644 index 000000000..7cc1115ac --- /dev/null +++ b/src/main/resources/twilio-php/helperMethod.mustache @@ -0,0 +1,248 @@ + /** + * Helper function for {{vendorExtensions.x-name}} + * + {{#requiredParams}} + {{^isPathParam}} + * @param {{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{#description}} {{{description}}}{{/description}} + {{/isPathParam}} + {{/requiredParams}} + {{#vendorExtensions.hasOptionalQueryParams}} + * @param array|Options $options Optional Arguments + {{/vendorExtensions.hasOptionalQueryParams}} + {{^vendorExtensions.hasOptionalQueryParams}} + {{#vendorExtensions.hasOptionalFormParams}} + * @param array|Options $options Optional Arguments + {{/vendorExtensions.hasOptionalFormParams}} + {{^vendorExtensions.hasOptionalFormParams}} + {{#vendorExtensions.hasOptionalHeaderParams}} + * @param array|Options $options Optional Arguments + {{/vendorExtensions.hasOptionalHeaderParams}} + {{/vendorExtensions.hasOptionalFormParams}} + {{/vendorExtensions.hasOptionalQueryParams}} + * @return Response {{#vendorExtensions.x-is-fetch-operation}}{{vendorExtensions.x-name}}ed{{/vendorExtensions.x-is-fetch-operation}}{{^vendorExtensions.x-is-fetch-operation}}{{vendorExtensions.x-name}}d{{/vendorExtensions.x-is-fetch-operation}} Response + * @throws TwilioException When an HTTP error occurs. + */ + private function _{{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}({{#requiredParams}}{{^isPathParam}}{{^vendorExtensions.x-serialize-map}}{{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{#vendorExtensions.x-serialize-map}}array ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{^-last}}, {{/-last}}{{/isPathParam}}{{/requiredParams}}{{#vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}, {{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}, {{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}, {{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{/vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}array $options = []{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}array $options = []{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}array $options = []{{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}): Response + { + {{#vendorExtensions.hasOptionalQueryParams}} + $options = new Values($options); + + {{/vendorExtensions.hasOptionalQueryParams}} + {{^vendorExtensions.hasOptionalQueryParams}} + {{#vendorExtensions.hasOptionalFormParams}} + $options = new Values($options); + + {{/vendorExtensions.hasOptionalFormParams}} + {{^vendorExtensions.hasOptionalFormParams}} + {{#vendorExtensions.hasOptionalHeaderParams}} + $options = new Values($options); + + {{/vendorExtensions.hasOptionalHeaderParams}} + {{/vendorExtensions.hasOptionalFormParams}} + {{/vendorExtensions.hasOptionalQueryParams}} + {{#queryParams.0}} + $params = Values::of([ + {{#queryParams}} + {{#required}} + {{^vendorExtensions.x-prefixed-collapsible-map}} + {{^vendorExtensions.x-serialize}} + '{{baseName}}' => + ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}, + {{/vendorExtensions.x-serialize}} + {{#vendorExtensions.x-serialize}} + {{^vendorExtensions.x-serialize-map}} + '{{baseName}}' => + {{vendorExtensions.x-serialize}}(${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}), + {{/vendorExtensions.x-serialize-map}} + {{#vendorExtensions.x-serialize-map}} + '{{baseName}}' => + {{vendorExtensions.x-serialize}}(${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}, function ($e) { return {{^vendorExtensions.x-serialize-array-of-array}}$e{{/vendorExtensions.x-serialize-array-of-array}}{{#vendorExtensions.x-serialize-array-of-array}}{{.}}($e){{/vendorExtensions.x-serialize-array-of-array}}; }), + {{/vendorExtensions.x-serialize-map}} + {{/vendorExtensions.x-serialize}} + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/required}} + {{/queryParams}} + {{#queryParams}} + {{^required}} + {{^vendorExtensions.x-prefixed-collapsible-map}} + {{^vendorExtensions.x-serialize}} + '{{baseName}}' => + $options['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}'], + {{/vendorExtensions.x-serialize}} + {{#vendorExtensions.x-serialize}} + {{^vendorExtensions.x-serialize-map}} + '{{baseName}}' => + {{vendorExtensions.x-serialize}}($options['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}']), + {{/vendorExtensions.x-serialize-map}} + {{#vendorExtensions.x-serialize-map}} + '{{baseName}}' => + {{vendorExtensions.x-serialize}}($options['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}'], function ($e) { return {{^vendorExtensions.x-serialize-array-of-array}}$e{{/vendorExtensions.x-serialize-array-of-array}}{{#vendorExtensions.x-serialize-array-of-array}}{{.}}($e){{/vendorExtensions.x-serialize-array-of-array}}; }), + {{/vendorExtensions.x-serialize-map}} + {{/vendorExtensions.x-serialize}} + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/required}} + {{/queryParams}} + ]); + {{#queryParams}} + {{#required}} + {{#vendorExtensions.x-prefixed-collapsible-map}} + $params = \array_merge($params, Serialize::prefixedCollapsibleMap(${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}, 'AddOns')); + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/required}} + {{/queryParams}} + {{#queryParams}} + {{^required}} + {{#vendorExtensions.x-prefixed-collapsible-map}} + $params = \array_merge($params, Serialize::prefixedCollapsibleMap($options['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}'], 'AddOns')); + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/required}} + {{/queryParams}} + + {{/queryParams.0}} + {{#formParams.0}} + $data = Values::of([ + {{#requiredParams}} + {{#isFormParam}} + {{^vendorExtensions.x-prefixed-collapsible-map}} + {{^vendorExtensions.x-serialize}} + '{{baseName}}' => + ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}, + {{/vendorExtensions.x-serialize}} + {{#vendorExtensions.x-serialize}} + {{^vendorExtensions.x-serialize-map}} + '{{baseName}}' => + {{vendorExtensions.x-serialize}}(${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}), + {{/vendorExtensions.x-serialize-map}} + {{#vendorExtensions.x-serialize-map}} + '{{baseName}}' => + {{vendorExtensions.x-serialize}}(${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}},function ($e) { return {{^vendorExtensions.x-serialize-array-of-array}}$e{{/vendorExtensions.x-serialize-array-of-array}}{{#vendorExtensions.x-serialize-array-of-array}}{{.}}($e){{/vendorExtensions.x-serialize-array-of-array}}; }), + {{/vendorExtensions.x-serialize-map}} + {{/vendorExtensions.x-serialize}} + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/isFormParam}} + {{/requiredParams}} + {{#optionalParams}} + {{#isFormParam}} + {{^vendorExtensions.x-prefixed-collapsible-map}} + {{^vendorExtensions.x-serialize}} + '{{baseName}}' => + $options['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}'], + {{/vendorExtensions.x-serialize}} + {{#vendorExtensions.x-serialize}} + {{^vendorExtensions.x-serialize-map}} + '{{baseName}}' => + {{vendorExtensions.x-serialize}}($options['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}']), + {{/vendorExtensions.x-serialize-map}} + {{#vendorExtensions.x-serialize-map}} + '{{baseName}}' => + {{vendorExtensions.x-serialize}}($options['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}'], function ($e) { return {{^vendorExtensions.x-serialize-array-of-array}}$e{{/vendorExtensions.x-serialize-array-of-array}}{{#vendorExtensions.x-serialize-array-of-array}}{{.}}($e){{/vendorExtensions.x-serialize-array-of-array}}; }), + {{/vendorExtensions.x-serialize-map}} + {{/vendorExtensions.x-serialize}} + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/isFormParam}} + {{/optionalParams}} + ]); + {{#requiredParams}} + {{#isFormParam}} + {{#vendorExtensions.x-prefixed-collapsible-map}} + $data = \array_merge($data, Serialize::prefixedCollapsibleMap($options['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}'], 'AddOns')); + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/isFormParam}} + {{/requiredParams}} + {{#optionalParams}} + {{#isFormParam}} + {{#vendorExtensions.x-prefixed-collapsible-map}} + $data = \array_merge($data, Serialize::prefixedCollapsibleMap($options['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}'], 'AddOns')); + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/isFormParam}} + {{/optionalParams}} + + {{/formParams.0}} + $headers = Values::of([{{^consumes}}'Content-Type' => 'application/x-www-form-urlencoded'{{/consumes}}{{#consumes}}{{#-first}}'Content-Type' => '{{{mediaType}}}'{{/-first}}{{/consumes}}{{^vendorExtensions.x-is-delete-operation}}{{#produces}}{{#-first}}, 'Accept' => '{{{mediaType}}}'{{/-first}}{{/produces}}{{/vendorExtensions.x-is-delete-operation}} {{#headerParams}}{{#required}}, '{{baseName}}' => + ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}}, '{{baseName}}' => $options['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}']{{/required}}{{/headerParams}}]); + {{#bodyParams.0}} + $data = ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}->toArray(); + {{/bodyParams.0}} + return $this->version->handleRequest('{{httpMethod}}', $this->uri{{#queryParams.0}}, $params{{/queryParams.0}}{{^queryParams}}, []{{/queryParams}}{{#formParams.0}}, $data{{/formParams.0}}{{^formParams}}{{#bodyParams.0}}, $data{{/bodyParams.0}}{{^bodyParams}}, []{{/bodyParams}}{{/formParams}}, $headers, "{{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}"); + } + + /** + * {{vendorExtensions.x-name}} the {{apiName}}Instance + * + {{#requiredParams}} + {{^isPathParam}} + * @param {{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{#description}} {{{description}}}{{/description}} + {{/isPathParam}} + {{/requiredParams}} + {{#vendorExtensions.hasOptionalQueryParams}} + * @param array|Options $options Optional Arguments + {{/vendorExtensions.hasOptionalQueryParams}} + {{^vendorExtensions.hasOptionalQueryParams}} + {{#vendorExtensions.hasOptionalFormParams}} + * @param array|Options $options Optional Arguments + {{/vendorExtensions.hasOptionalFormParams}} + {{^vendorExtensions.hasOptionalFormParams}} + {{#vendorExtensions.hasOptionalHeaderParams}} + * @param array|Options $options Optional Arguments + {{/vendorExtensions.hasOptionalHeaderParams}} + {{/vendorExtensions.hasOptionalFormParams}} + {{/vendorExtensions.hasOptionalQueryParams}} + {{^vendorExtensions.x-is-delete-operation}} + * @return {{apiName}}Instance {{#vendorExtensions.x-is-fetch-operation}}{{vendorExtensions.x-name}}ed{{/vendorExtensions.x-is-fetch-operation}}{{^vendorExtensions.x-is-fetch-operation}}{{vendorExtensions.x-name}}d{{/vendorExtensions.x-is-fetch-operation}} {{apiName}}Instance + {{/vendorExtensions.x-is-delete-operation}} + {{#vendorExtensions.x-is-delete-operation}} + * @return bool True if delete succeeds, false otherwise + {{/vendorExtensions.x-is-delete-operation}} + * @throws TwilioException When an HTTP error occurs. + */ + public function {{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}({{#requiredParams}}{{^isPathParam}}{{^vendorExtensions.x-serialize-map}}{{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{#vendorExtensions.x-serialize-map}}array ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{^-last}}, {{/-last}}{{/isPathParam}}{{/requiredParams}}{{#vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}, {{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}, {{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}, {{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{/vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}array $options = []{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}array $options = []{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}array $options = []{{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}): {{#vendorExtensions.x-is-delete-operation}}bool{{/vendorExtensions.x-is-delete-operation}}{{^vendorExtensions.x-is-delete-operation}}{{apiName}}Instance{{/vendorExtensions.x-is-delete-operation}} + { + $response = $this->_{{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}({{#requiredParams}}{{^isPathParam}}{{^vendorExtensions.x-serialize-map}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{#vendorExtensions.x-serialize-map}}${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{^-last}}, {{/-last}}{{/isPathParam}}{{/requiredParams}}{{#vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}, {{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}, {{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}, {{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{/vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}$options{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}$options{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}$options{{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}); + {{^vendorExtensions.x-is-delete-operation}}return new {{apiName}}Instance( + $this->version, + $response->getContent(){{#optionalParams}}{{#isPathParam}}, + $this->solution['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}']{{/isPathParam}}{{/optionalParams}}{{#requiredParams}}{{#isPathParam}}, + $this->solution['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}']{{/isPathParam}}{{/requiredParams}} + );{{/vendorExtensions.x-is-delete-operation}} + {{#vendorExtensions.x-is-delete-operation}}return true;{{/vendorExtensions.x-is-delete-operation}} + } + + /** + * {{vendorExtensions.x-name}} the {{apiName}}Instance with Metadata + * + {{#requiredParams}} + {{^isPathParam}} + * @param {{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{#description}} {{{description}}}{{/description}} + {{/isPathParam}} + {{/requiredParams}} + {{#vendorExtensions.hasOptionalQueryParams}} + * @param array|Options $options Optional Arguments + {{/vendorExtensions.hasOptionalQueryParams}} + {{^vendorExtensions.hasOptionalQueryParams}} + {{#vendorExtensions.hasOptionalFormParams}} + * @param array|Options $options Optional Arguments + {{/vendorExtensions.hasOptionalFormParams}} + {{^vendorExtensions.hasOptionalFormParams}} + {{#vendorExtensions.hasOptionalHeaderParams}} + * @param array|Options $options Optional Arguments + {{/vendorExtensions.hasOptionalHeaderParams}} + {{/vendorExtensions.hasOptionalFormParams}} + {{/vendorExtensions.hasOptionalQueryParams}} + * @return ResourceMetadata The {{#vendorExtensions.x-is-fetch-operation}}{{vendorExtensions.x-name}}ed{{/vendorExtensions.x-is-fetch-operation}}{{^vendorExtensions.x-is-fetch-operation}}{{vendorExtensions.x-name}}d{{/vendorExtensions.x-is-fetch-operation}} Resource with Metadata + * @throws TwilioException When an HTTP error occurs. + */ + public function {{#lambda.camelcase}}{{vendorExtensions.x-name}}WithMetadata{{/lambda.camelcase}}({{#requiredParams}}{{^isPathParam}}{{^vendorExtensions.x-serialize-map}}{{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{#vendorExtensions.x-serialize-map}}array ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{^-last}}, {{/-last}}{{/isPathParam}}{{/requiredParams}}{{#vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}, {{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}, {{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}, {{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{/vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}array $options = []{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}array $options = []{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}array $options = []{{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}): ResourceMetadata + { + $response = $this->_{{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}({{#requiredParams}}{{^isPathParam}}{{^vendorExtensions.x-serialize-map}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{#vendorExtensions.x-serialize-map}}${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{^-last}}, {{/-last}}{{/isPathParam}}{{/requiredParams}}{{#vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}, {{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}, {{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}, {{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{/vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}$options{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}$options{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}$options{{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}); + {{^vendorExtensions.x-is-delete-operation}}$resource = new {{apiName}}Instance( + $this->version, + $response->getContent(){{#optionalParams}}{{#isPathParam}}, + $this->solution['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}']{{/isPathParam}}{{/optionalParams}}{{#requiredParams}}{{#isPathParam}}, + $this->solution['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}']{{/isPathParam}}{{/requiredParams}} + );{{/vendorExtensions.x-is-delete-operation}} + return new ResourceMetadata( + {{^vendorExtensions.x-is-delete-operation}}$resource{{/vendorExtensions.x-is-delete-operation}}{{#vendorExtensions.x-is-delete-operation}}null{{/vendorExtensions.x-is-delete-operation}}, + $response->getStatusCode(), + $response->getHeaders() + ); + } diff --git a/src/main/resources/twilio-php/imports.mustache b/src/main/resources/twilio-php/imports.mustache index d98ad2670..3d50933bb 100644 --- a/src/main/resources/twilio-php/imports.mustache +++ b/src/main/resources/twilio-php/imports.mustache @@ -5,7 +5,13 @@ use Twilio\Options; use Twilio\Stream; use Twilio\Values; use Twilio\Version; +use Twilio\ApiV1Version; use Twilio\InstanceContext; +use Twilio\Http\Response; +use Twilio\Metadata\ArrayMetadata; +use Twilio\Metadata\PageMetadata; +use Twilio\Metadata\ResourceMetadata; +use Twilio\Metadata\StreamMetadata; use Twilio\Deserialize; use Twilio\Serialize; use Twilio\Base\PhoneNumberCapabilities; @@ -14,4 +20,4 @@ use Twilio\Rest\{{domainName}}\{{apiVersionClass}}\{{parent}}List; {{/metaProperties.listImportProperties}} {{#metaProperties.contextImportProperties}} use Twilio\Rest\{{domainName}}\{{apiVersionClass}}\{{parent}}List; -{{/metaProperties.contextImportProperties}} \ No newline at end of file +{{/metaProperties.contextImportProperties}} diff --git a/src/main/resources/twilio-php/instance.mustache b/src/main/resources/twilio-php/instance.mustache index a2afae68b..c56bcb0c2 100644 --- a/src/main/resources/twilio-php/instance.mustache +++ b/src/main/resources/twilio-php/instance.mustache @@ -7,6 +7,7 @@ namespace Twilio\Rest\{{domainName}}\{{version}}{{namespaceSubPart}}; {{>imports}} +{{^isApiV1}} {{#responseModels.0}} /** {{#responseModels}} @@ -128,5 +129,9 @@ class {{apiName}}Instance extends InstanceResource return '[Twilio.{{domainName}}.{{version}}.{{apiName}}Instance{{#metaProperties.x-is-context-operation}} ' . \implode(' ', $context) . '{{/metaProperties.x-is-context-operation}}]'; } } +{{/isApiV1}} +{{#isApiV1}} +{{>instanceClasses}} +{{/isApiV1}} {{/resources}} diff --git a/src/main/resources/twilio-php/instanceClass.mustache b/src/main/resources/twilio-php/instanceClass.mustache new file mode 100644 index 000000000..92d802968 --- /dev/null +++ b/src/main/resources/twilio-php/instanceClass.mustache @@ -0,0 +1,130 @@ +{{#resources}} +{{#isApiV1}} +licenseInfo}} + +namespace Twilio\Rest\{{domainName}}\{{version}}{{namespaceSubPart}}; + +{{>imports}} + +{{#responseInstanceModels}} +/** +{{#vars}} * @property {{{dataType}}} ${{#lambda.customcamelcase}}{{baseName}}{{/lambda.customcamelcase}} +{{/vars}} */ +class {{classname}}Instance extends InstanceResource +{ +{{#metaProperties.contextImportProperties}} + protected $_{{#lambda.camelcase}}{{mountName}}{{/lambda.camelcase}}; + {{#-last}} + + {{/-last}} +{{/metaProperties.contextImportProperties}} + /** + * Initialize the {{classname}}Instance + * + * @param Version $version Version that contains the resource + * @param mixed[] $payload The response payload + {{#requiredPathParams}} + * @param {{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{#description}} {{{description}}}{{/description}} + {{/requiredPathParams}} + */ + public function __construct(Version $version, array $payload{{#requiredPathParams}}{{#vendorExtensions.x-is-parent-param}}, {{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-is-parent-param}}{{^vendorExtensions.x-is-parent-param}}, ?{{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}} = null{{/vendorExtensions.x-is-parent-param}}{{/requiredPathParams}}) + { + {{^isApiV1}}parent::__construct($version);{{/isApiV1}}{{#isApiV1}}$apiV1Version = new ApiV1Version($version->getDomain(), $version->version); + parent::__construct($apiV1Version);{{/isApiV1}} + + // Marshaled Properties + $this->properties = [ + {{#vars}} + {{^vendorExtensions.x-deserialize}} + '{{#lambda.customcamelcase}}{{baseName}}{{/lambda.customcamelcase}}' => Values::array_get($payload, '{{name}}'), + {{/vendorExtensions.x-deserialize}} + {{#vendorExtensions.x-deserialize}} + '{{#lambda.customcamelcase}}{{baseName}}{{/lambda.customcamelcase}}' => {{.}}(Values::array_get($payload, '{{name}}')), + {{/vendorExtensions.x-deserialize}} + {{/vars}} + ]; + + $this->solution = [{{#requiredPathParams}}{{#vendorExtensions.x-is-parent-param}}'{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}' => ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}, {{/vendorExtensions.x-is-parent-param}}{{^vendorExtensions.x-is-parent-param}}'{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}' => ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}} ?: $this->properties['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}'], {{/vendorExtensions.x-is-parent-param}}{{/requiredPathParams}}]; + } + +{{#metaProperties.x-is-context-operation}} + /** + * Generate an instance context for the instance, the context is capable of + * performing various actions. All instance actions are proxied to the context + * + * @return {{apiName}}Context Context for this {{apiName}}Instance + */ + protected function proxy(): {{apiName}}Context + { + if (!$this->context) { + $this->context = new {{apiName}}Context( + $this->version{{#requiredPathParams.0}},{{/requiredPathParams.0}} + {{#requiredPathParams}} + $this->solution['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}']{{^-last}},{{/-last}} + {{/requiredPathParams}} + ); + } + + return $this->context; + } + +{{/metaProperties.x-is-context-operation}} +{{#apiOperations}} +{{#vendorExtensions.instanceOperation}}{{>method}} + return $this->proxy()->{{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}({{#requiredParams}}{{^isPathParam}}${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{^-last}}, {{/-last}}{{/isPathParam}}{{/requiredParams}}{{#vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}, {{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}, {{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}, {{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{/vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}$options{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}$options{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}$options{{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}); + } + +{{/vendorExtensions.instanceOperation}} +{{/apiOperations}} +{{#metaProperties.contextImportProperties}} + /** + * Access the {{#lambda.camelcase}}{{mountName}}{{/lambda.camelcase}} + */ + protected function get{{#lambda.titlecase}}{{mountName}}{{/lambda.titlecase}}(): {{filename}}List + { + return $this->proxy()->{{#lambda.camelcase}}{{mountName}}{{/lambda.camelcase}}; + } + +{{/metaProperties.contextImportProperties}} + /** + * Magic getter to access properties + * + * @param string $name Property to access + * @return mixed The requested property + * @throws TwilioException For unknown properties + */ + public function __get(string $name) + { + if (\array_key_exists($name, $this->properties)) { + return $this->properties[$name]; + } + + if (\property_exists($this, '_' . $name)) { + $method = 'get' . \ucfirst($name); + return $this->$method(); + } + + throw new TwilioException('Unknown property: ' . $name); + } + + /** + * Provide a friendly representation + * + * @return string Machine friendly representation + */ + public function __toString(): string + { + {{#metaProperties.x-is-context-operation}} + $context = []; + foreach ($this->solution as $key => $value) { + $context[] = "$key=$value"; + } + {{/metaProperties.x-is-context-operation}} + return '[Twilio.{{domainName}}.{{version}}.{{classname}}Instance{{#metaProperties.x-is-context-operation}} ' . \implode(' ', $context) . '{{/metaProperties.x-is-context-operation}}]'; + } +} +{{/responseInstanceModels}} +{{/isApiV1}} +{{/resources}} diff --git a/src/main/resources/twilio-php/instanceClasses.mustache b/src/main/resources/twilio-php/instanceClasses.mustache new file mode 100644 index 000000000..51b37a946 --- /dev/null +++ b/src/main/resources/twilio-php/instanceClasses.mustache @@ -0,0 +1,120 @@ +{{#isApiV1}} +{{#responseInstanceModels}} +{{#vars}}/** + * @property {{{dataType}}} ${{#lambda.customcamelcase}}{{baseName}}{{/lambda.customcamelcase}} + */{{/vars}} +class {{classname}}Instance extends InstanceResource +{ +{{#metaProperties.contextImportProperties}} + protected $_{{#lambda.camelcase}}{{mountName}}{{/lambda.camelcase}}; + {{#-last}} + + {{/-last}} +{{/metaProperties.contextImportProperties}} + /** + * Initialize the {{classname}}Instance + * + * @param Version $version Version that contains the resource + * @param mixed[] $payload The response payload + {{#requiredPathParams}} + * @param {{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{#description}} {{{description}}}{{/description}} + {{/requiredPathParams}} + */ + public function __construct(Version $version, array $payload{{#requiredPathParams}}{{#vendorExtensions.x-is-parent-param}}, {{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-is-parent-param}}{{^vendorExtensions.x-is-parent-param}}, ?{{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}} = null{{/vendorExtensions.x-is-parent-param}}{{/requiredPathParams}}) + { + {{^isApiV1}}parent::__construct($version);{{/isApiV1}}{{#isApiV1}}$apiV1Version = new ApiV1Version($version->getDomain(), $version->version); + parent::__construct($apiV1Version);{{/isApiV1}} + + // Marshaled Properties + $this->properties = [ + {{#vars}} + {{^vendorExtensions.x-deserialize}} + '{{#lambda.customcamelcase}}{{baseName}}{{/lambda.customcamelcase}}' => Values::array_get($payload, '{{name}}'), + {{/vendorExtensions.x-deserialize}} + {{#vendorExtensions.x-deserialize}} + '{{#lambda.customcamelcase}}{{baseName}}{{/lambda.customcamelcase}}' => {{.}}(Values::array_get($payload, '{{name}}')), + {{/vendorExtensions.x-deserialize}} + {{/vars}} + ]; + + $this->solution = [{{#requiredPathParams}}{{#vendorExtensions.x-is-parent-param}}'{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}' => ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}, {{/vendorExtensions.x-is-parent-param}}{{^vendorExtensions.x-is-parent-param}}'{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}' => ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}} ?: $this->properties['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}'], {{/vendorExtensions.x-is-parent-param}}{{/requiredPathParams}}]; + } + +{{#metaProperties.x-is-context-operation}} + /** + * Generate an instance context for the instance, the context is capable of + * performing various actions. All instance actions are proxied to the context + * + * @return {{classname}}Context Context for this {{classname}}Instance + */ + protected function proxy(): {{classname}}Context + { + if (!$this->context) { + $this->context = new {{classname}}Context( + $this->version{{#requiredPathParams.0}},{{/requiredPathParams.0}} + {{#requiredPathParams}} + $this->solution['{{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}']{{^-last}},{{/-last}} + {{/requiredPathParams}} + ); + } + + return $this->context; + } + +{{/metaProperties.x-is-context-operation}} +{{#apiOperations}} +{{#vendorExtensions.instanceOperation}}{{>method}} + return $this->proxy()->{{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}({{#requiredParams}}{{^isPathParam}}${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{^-last}}, {{/-last}}{{/isPathParam}}{{/requiredParams}}{{#vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}, {{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}, {{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}, {{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{/vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}$options{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}$options{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}$options{{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}); + } + +{{/vendorExtensions.instanceOperation}} +{{/apiOperations}} +{{#metaProperties.contextImportProperties}} + /** + * Access the {{#lambda.camelcase}}{{mountName}}{{/lambda.camelcase}} + */ + protected function get{{#lambda.titlecase}}{{mountName}}{{/lambda.titlecase}}(): {{filename}}List + { + return $this->proxy()->{{#lambda.camelcase}}{{mountName}}{{/lambda.camelcase}}; + } + +{{/metaProperties.contextImportProperties}} + /** + * Magic getter to access properties + * + * @param string $name Property to access + * @return mixed The requested property + * @throws TwilioException For unknown properties + */ + public function __get(string $name) + { + if (\array_key_exists($name, $this->properties)) { + return $this->properties[$name]; + } + + if (\property_exists($this, '_' . $name)) { + $method = 'get' . \ucfirst($name); + return $this->$method(); + } + + throw new TwilioException('Unknown property: ' . $name); + } + + /** + * Provide a friendly representation + * + * @return string Machine friendly representation + */ + public function __toString(): string + { + {{#metaProperties.x-is-context-operation}} + $context = []; + foreach ($this->solution as $key => $value) { + $context[] = "$key=$value"; + } + {{/metaProperties.x-is-context-operation}} + return '[Twilio.{{domainName}}.{{version}}.{{classname}}Instance{{#metaProperties.x-is-context-operation}} ' . \implode(' ', $context) . '{{/metaProperties.x-is-context-operation}}]'; + } +} +{{/responseInstanceModels}} +{{/isApiV1}} diff --git a/src/main/resources/twilio-php/list.mustache b/src/main/resources/twilio-php/list.mustache index 5c3569c90..e975e8d86 100644 --- a/src/main/resources/twilio-php/list.mustache +++ b/src/main/resources/twilio-php/list.mustache @@ -50,7 +50,8 @@ class {{apiName}}List extends ListResource Version $version{{#requiredPathParams}}{{#vendorExtensions.x-is-parent-param}}, {{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-is-parent-param}}{{/requiredPathParams}} ) { - parent::__construct($version); + {{^isApiV1}}parent::__construct($version);{{/isApiV1}}{{#isApiV1}}$apiV1Version = new ApiV1Version($version->getDomain(), $version->version); + parent::__construct($apiV1Version);{{/isApiV1}} // Path Solution $this->solution = [{{#requiredPathParams}}{{#vendorExtensions.x-is-parent-param}} @@ -67,8 +68,8 @@ class {{apiName}}List extends ListResource {{#apiOperations}} {{^vendorExtensions.x-ignore}} {{#vendorExtensions.listOperation}} -{{^vendorExtensions.x-is-read-operation}}{{>method}} -{{>contextMethod}} +{{^vendorExtensions.x-is-read-operation}} +{{>helperMethod}} {{/vendorExtensions.x-is-read-operation}} {{/vendorExtensions.listOperation}} diff --git a/src/main/resources/twilio-php/listRead.mustache b/src/main/resources/twilio-php/listRead.mustache index ee092c781..140be1df9 100644 --- a/src/main/resources/twilio-php/listRead.mustache +++ b/src/main/resources/twilio-php/listRead.mustache @@ -22,6 +22,35 @@ return \iterator_to_array($this->stream({{#vendorExtensions.x-has-non-pagination-params}}$options, {{/vendorExtensions.x-has-non-pagination-params}}$limit, $pageSize), false); } + /** + * Reads {{apiName}}Instance records from the API as a list + * Unlike stream(), this operation is eager and will load `limit` records into + * memory before returning. + * + {{#vendorExtensions.x-has-non-pagination-params}} + * @param array|Options $options Optional Arguments + {{/vendorExtensions.x-has-non-pagination-params}} + * @param int $limit Upper limit for the number of records to return. read() + * guarantees to never return more than limit. Default is no + * limit + * @param mixed $pageSize Number of records to fetch per request, when not set + * will use the default value of 50 records. If no + * page_size is defined but a limit is defined, read() + * will attempt to read the limit with the most + * efficient page size, i.e. min(limit, 1000) + * @return ArrayMetadata Array of results along with metadata + */ + public function readWithMetadata({{#vendorExtensions.x-has-non-pagination-params}}array $options = [], {{/vendorExtensions.x-has-non-pagination-params}}?int $limit = null, $pageSize = null): ArrayMetadata + { + $streamWithMetadata = $this->streamWithMetadata({{#vendorExtensions.x-has-non-pagination-params}}$options, {{/vendorExtensions.x-has-non-pagination-params}}$limit, $pageSize); + $readResponse = \iterator_to_array($streamWithMetadata, false); + return new ArrayMetadata( + $readResponse, + $streamWithMetadata->getStatusCode(), + $streamWithMetadata->getHeaders() + ); + } + /** * Streams {{apiName}}Instance records from the API as a generator stream. * This operation lazily loads records as efficiently as possible until the @@ -45,7 +74,8 @@ */ public function stream({{#vendorExtensions.x-has-non-pagination-params}}array $options = [], {{/vendorExtensions.x-has-non-pagination-params}}?int $limit = null, $pageSize = null): Stream { - $limits = $this->version->readLimits($limit, $pageSize); + {{#isApiV1}}{{#vendorExtensions.x-has-non-pagination-params}}$pageSize = $options['pageSize'] ?? $pageSize; + {{/vendorExtensions.x-has-non-pagination-params}}{{/isApiV1}}$limits = $this->version->readLimits($limit, $pageSize); $page = $this->page({{#vendorExtensions.x-has-non-pagination-params}}$options, {{/vendorExtensions.x-has-non-pagination-params}}$limits['pageSize']); @@ -53,26 +83,62 @@ } /** - * Retrieve a single page of {{apiName}}Instance records from the API. - * Request is executed immediately + * Streams {{apiName}}Instance records from the API as a generator stream and returns result with Metadata + * This operation lazily loads records as efficiently as possible until the + * limit + * is reached. + * The results are returned as a generator, so this operation is memory + * efficient. + * + {{#vendorExtensions.x-has-non-pagination-params}} + * @param array|Options $options Optional Arguments + {{/vendorExtensions.x-has-non-pagination-params}} + * @param int $limit Upper limit for the number of records to return. stream() + * guarantees to never return more than limit. Default is no + * limit + * @param mixed $pageSize Number of records to fetch per request, when not set + * will use the default value of 50 records. If no + * page_size is defined but a limit is defined, stream() + * will attempt to read the limit with the most + * efficient page size, i.e. min(limit, 1000) + * @return StreamMetadata stream of results with metadata + */ + public function streamWithMetadata({{#vendorExtensions.x-has-non-pagination-params}}array $options = [], {{/vendorExtensions.x-has-non-pagination-params}}?int $limit = null, $pageSize = null): StreamMetadata + { + {{#isApiV1}}{{#vendorExtensions.x-has-non-pagination-params}}$pageSize = $options['pageSize'] ?? $pageSize; + {{/vendorExtensions.x-has-non-pagination-params}}{{/isApiV1}}$limits = $this->version->readLimits($limit, $pageSize); + + $pageWithMetadata = $this->pageWithMetadata({{#vendorExtensions.x-has-non-pagination-params}}$options, {{/vendorExtensions.x-has-non-pagination-params}}$limits['pageSize']); + + $stream = $this->version->stream($pageWithMetadata->getPage(), $limits['limit'], $limits['pageLimit']); + + return new StreamMetadata( + $stream, + $pageWithMetadata->getStatusCode(), + $pageWithMetadata->getHeaders() + ); + } + + /** + * Helper function for Page * * @param mixed $pageSize Number of records to return, defaults to 50 - * @param string $pageToken PageToken provided by the API - * @param mixed $pageNumber Page Number, this value is simply for client state - * @return {{apiName}}Page Page of {{apiName}}Instance + * {{^isApiV1}}@param string $pageToken PageToken provided by the API + * @param mixed $pageNumber Page Number, this value is simply for client state{{/isApiV1}} + * @return Response Paged Response */ - public function page( + private function _page( {{#vendorExtensions.x-has-non-pagination-params}}array $options = [], {{/vendorExtensions.x-has-non-pagination-params}}$pageSize = Values::NONE, - string $pageToken = Values::NONE, - $pageNumber = Values::NONE - ): {{apiName}}Page + {{^isApiV1}}string $pageToken = Values::NONE, + $pageNumber = Values::NONE{{/isApiV1}} + ): Response { {{#vendorExtensions.x-has-non-pagination-params}} $options = new Values($options); {{/vendorExtensions.x-has-non-pagination-params}} - $params = Values::of([ + $params = Values::of([{{#vendorExtensions.x-has-non-pagination-params}} {{#vendorExtensions.optionFileParams}} {{^vendorExtensions.x-serialize}} '{{{baseName}}}' => @@ -106,18 +172,64 @@ {{/vendorExtensions.x-serialize-map}} {{/vendorExtensions.x-serialize}} {{/required}} - {{/queryParams}} - 'PageToken' => $pageToken, - 'Page' => $pageNumber, + {{/queryParams}}{{/vendorExtensions.x-has-non-pagination-params}} + {{^isApiV1}}'PageToken' => $pageToken, + 'Page' => $pageNumber,{{/isApiV1}} 'PageSize' => $pageSize, ]); $headers = Values::of([{{^consumes}}'Content-Type' => 'application/x-www-form-urlencoded'{{/consumes}}{{#consumes}}{{#-first}}'Content-Type' => '{{{mediaType}}}'{{/-first}}{{/consumes}}{{#produces}}{{#-first}}, 'Accept' => '{{{mediaType}}}'{{/-first}}{{/produces}}]); - $response = $this->version->page('{{httpMethod}}', $this->uri, $params, [], $headers); + return $this->version->page('{{httpMethod}}', $this->uri, $params, [], $headers); + } + + /** + * Retrieve a single page of {{apiName}}Instance records from the API. + * Request is executed immediately + * + * @param mixed $pageSize Number of records to return, defaults to 50 + * {{^isApiV1}}@param string $pageToken PageToken provided by the API + * @param mixed $pageNumber Page Number, this value is simply for client state{{/isApiV1}} + * @return {{apiName}}Page Page of {{apiName}}Instance + */ + public function page( + {{#vendorExtensions.x-has-non-pagination-params}}array $options = [], + {{/vendorExtensions.x-has-non-pagination-params}}$pageSize = Values::NONE, + {{^isApiV1}}string $pageToken = Values::NONE, + $pageNumber = Values::NONE{{/isApiV1}} + ): {{apiName}}Page + { + $response = $this->_page({{#vendorExtensions.x-has-non-pagination-params}}$options,{{/vendorExtensions.x-has-non-pagination-params}} $pageSize,{{^isApiV1}} $pageToken, $pageNumber{{/isApiV1}}); return new {{apiName}}Page($this->version, $response, $this->solution); } + /** + * Retrieve a single page of {{apiName}}Instance records with metadata + * Request is executed immediately + * + * @param mixed $pageSize Number of records to return, defaults to 50 + * {{^isApiV1}}@param string $pageToken PageToken provided by the API + * @param mixed $pageNumber Page Number, this value is simply for client state{{/isApiV1}} + * @return PageMetadata of {{apiName}}Instance + */ + public function pageWithMetadata( + {{#vendorExtensions.x-has-non-pagination-params}}array $options = [], + {{/vendorExtensions.x-has-non-pagination-params}}$pageSize = Values::NONE, + {{^isApiV1}}string $pageToken = Values::NONE, + $pageNumber = Values::NONE{{/isApiV1}} + ): PageMetadata + { + $response = $this->_page({{#vendorExtensions.x-has-non-pagination-params}}$options,{{/vendorExtensions.x-has-non-pagination-params}} $pageSize,{{^isApiV1}} $pageToken, $pageNumber{{/isApiV1}}); + + $resource = new {{apiName}}Page($this->version, $response, $this->solution); + + return new PageMetadata( + $resource, + $response->getStatusCode(), + $response->getHeaders() + ); + } + /** * Retrieve a specific page of {{apiName}}Instance records from the API. * Request is executed immediately diff --git a/src/main/resources/twilio-php/method.mustache b/src/main/resources/twilio-php/method.mustache index 4e9c91954..afa46638b 100644 --- a/src/main/resources/twilio-php/method.mustache +++ b/src/main/resources/twilio-php/method.mustache @@ -1,5 +1,5 @@ /** - * {{vendorExtensions.x-name}} the {{apiName}}Instance + * {{vendorExtensions.x-name}} the {{^isApiV1}}{{apiName}}{{/isApiV1}}{{#isApiV1}}{{returnBaseType}}{{/isApiV1}}Instance * {{#requiredParams}} {{^isPathParam}} @@ -20,12 +20,12 @@ {{/vendorExtensions.hasOptionalFormParams}} {{/vendorExtensions.hasOptionalQueryParams}} {{^vendorExtensions.x-is-delete-operation}} - * @return {{apiName}}Instance {{#vendorExtensions.x-is-fetch-operation}}{{vendorExtensions.x-name}}ed{{/vendorExtensions.x-is-fetch-operation}}{{^vendorExtensions.x-is-fetch-operation}}{{vendorExtensions.x-name}}d{{/vendorExtensions.x-is-fetch-operation}} {{apiName}}Instance + * @return {{^isApiV1}}{{apiName}}{{/isApiV1}}{{#isApiV1}}{{returnBaseType}}{{/isApiV1}}Instance {{#vendorExtensions.x-is-fetch-operation}}{{vendorExtensions.x-name}}ed{{/vendorExtensions.x-is-fetch-operation}}{{^vendorExtensions.x-is-fetch-operation}}{{vendorExtensions.x-name}}d{{/vendorExtensions.x-is-fetch-operation}} {{^isApiV1}}{{apiName}}{{/isApiV1}}{{#isApiV1}}{{returnBaseType}}{{/isApiV1}}Instance {{/vendorExtensions.x-is-delete-operation}} {{#vendorExtensions.x-is-delete-operation}} * @return bool True if delete succeeds, false otherwise {{/vendorExtensions.x-is-delete-operation}} * @throws TwilioException When an HTTP error occurs. */ - public function {{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}({{#requiredParams}}{{^isPathParam}}{{^vendorExtensions.x-serialize-map}}{{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{#vendorExtensions.x-serialize-map}}array ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{^-last}}, {{/-last}}{{/isPathParam}}{{/requiredParams}}{{#vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}, {{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}, {{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}, {{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{/vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}array $options = []{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}array $options = []{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}array $options = []{{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}): {{#vendorExtensions.x-is-delete-operation}}bool{{/vendorExtensions.x-is-delete-operation}}{{^vendorExtensions.x-is-delete-operation}}{{apiName}}Instance{{/vendorExtensions.x-is-delete-operation}} + public function {{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}({{#requiredParams}}{{^isPathParam}}{{^vendorExtensions.x-serialize-map}}{{{dataType}}} ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{#vendorExtensions.x-serialize-map}}array ${{#lambda.camelcase}}{{baseName}}{{/lambda.camelcase}}{{/vendorExtensions.x-serialize-map}}{{^-last}}, {{/-last}}{{/isPathParam}}{{/requiredParams}}{{#vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}, {{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}, {{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}, {{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{/vendorExtensions.hasRequiredNonPathParams}}{{#vendorExtensions.hasOptionalQueryParams}}array $options = []{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{#vendorExtensions.hasOptionalFormParams}}array $options = []{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalQueryParams}}{{^vendorExtensions.hasOptionalFormParams}}{{#vendorExtensions.hasOptionalHeaderParams}}array $options = []{{/vendorExtensions.hasOptionalHeaderParams}}{{/vendorExtensions.hasOptionalFormParams}}{{/vendorExtensions.hasOptionalQueryParams}}): {{#vendorExtensions.x-is-delete-operation}}bool{{/vendorExtensions.x-is-delete-operation}}{{^vendorExtensions.x-is-delete-operation}}{{^isApiV1}}{{apiName}}{{/isApiV1}}{{#isApiV1}}{{returnBaseType}}{{/isApiV1}}Instance{{/vendorExtensions.x-is-delete-operation}} { diff --git a/src/main/resources/twilio-php/page.mustache b/src/main/resources/twilio-php/page.mustache index 1ea60d234..5f381acbf 100644 --- a/src/main/resources/twilio-php/page.mustache +++ b/src/main/resources/twilio-php/page.mustache @@ -4,10 +4,12 @@ namespace Twilio\Rest\{{domainName}}\{{version}}{{namespaceSubPart}}; use Twilio\Http\Response; -use Twilio\Page; +use Twilio\Page;{{#isApiV1}} +use Twilio\TokenPaginationPage; +use Twilio\ApiV1Version;{{/isApiV1}} use Twilio\Version; -class {{apiName}}Page extends Page +class {{apiName}}Page extends {{#isApiV1}}TokenPaginationPage{{/isApiV1}}{{^isApiV1}}Page{{/isApiV1}} { /** * @param Version $version Version that contains the resource @@ -16,7 +18,8 @@ class {{apiName}}Page extends Page */ public function __construct(Version $version, Response $response, array $solution) { - parent::__construct($version, $response); + {{^isApiV1}}parent::__construct($version, $response);{{/isApiV1}}{{#isApiV1}}$apiV1Version = new ApiV1Version($version->getDomain(), $version->version); + parent::__construct($apiV1Version, $response);{{/isApiV1}} // Path Solution $this->solution = $solution; diff --git a/src/main/resources/twilio-python/api-single.mustache b/src/main/resources/twilio-python/api-single.mustache index ae8ce0f37..f96d96165 100644 --- a/src/main/resources/twilio-python/api-single.mustache +++ b/src/main/resources/twilio-python/api-single.mustache @@ -3,11 +3,12 @@ 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 {{#instancePath}}from twilio.base.instance_context import InstanceContext{{/instancePath}} {{#responseModel}}from twilio.base.instance_resource import InstanceResource{{/responseModel}} from twilio.base.list_resource import ListResource from twilio.base.version import Version -{{#hasPaginationOperation}}from twilio.base.page import Page{{/hasPaginationOperation}} +{{#hasPaginationOperation}}{{#isApiV1}}from twilio.base.token_pagination import TokenPagination{{/isApiV1}}{{^isApiV1}}from twilio.base.page import Page{{/isApiV1}}{{/hasPaginationOperation}} {{#dependents}}from twilio.rest.{{domainPackage}}.{{apiVersion}}.{{namespaceSubPart}}.{{filename}} import {{resourceName}}List {{/dependents}} diff --git a/src/main/resources/twilio-python/context.handlebars b/src/main/resources/twilio-python/context.handlebars index 7481248ba..e06fc93c0 100644 --- a/src/main/resources/twilio-python/context.handlebars +++ b/src/main/resources/twilio-python/context.handlebars @@ -19,13 +19,12 @@ class {{apiName}}Context(InstanceContext): self._{{mountName}}: Optional[{{listName}}] = None{{/instanceDependent}}{{/dependents}} {{#operations}}{{#vendorExtensions.x-is-context-operation}} {{#vendorExtensions.x-is-update-operation}}{{^vendorExtensions.x-twilio.ignoreOperation}} - def {{vendorExtensions.x-name-lower}}(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + def _{{vendorExtensions.x-name-lower}}(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> tuple: """ - Update the {{instanceName}} - {{#allParams}} - :param {{paramName}}: {{{description}}}{{/allParams}} + Internal helper for {{vendorExtensions.x-name-lower}} operation - :returns: The updated {{instanceName}} + Returns: + tuple: (payload, status_code, headers) """ {{#bodyParam}}data = {{paramName}}.to_dict(){{/bodyParam}} {{^bodyParam}}data = values.of({ {{#allParams}}{{#isFormParam}} @@ -49,21 +48,45 @@ class {{apiName}}Context(InstanceContext): {{#allParams}}{{#isQueryParam}}{{#if vendorExtensions.x-prefixed-collapsible-map}}params.update({{vendorExtensions.x-serialize}}({{paramName}}, '{{vendorExtensions.x-prefixed-collapsible-map}}')) {{/if}}{{/isQueryParam}}{{/allParams}}{{/if}} - payload = self._version.update(method='{{vendorExtensions.x-http-method}}', uri=self._uri, data=data, headers=headers{{#if queryParams}}, params=params{{/if}}) + return self._version.update_with_response_info(method='{{vendorExtensions.x-http-method}}', uri=self._uri, data=data, headers=headers{{#if queryParams}}, params=params{{/if}}) + + def {{vendorExtensions.x-name-lower}}(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + """ + Update the {{instanceName}} + {{#allParams}} + :param {{paramName}}: {{{description}}}{{/allParams}} + :returns: The updated {{instanceName}} + """ + payload, _, _ = self._{{vendorExtensions.x-name-lower}}({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) return {{instanceName}}( self._version, payload{{#instancePathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/instancePathParams}} ) - async def {{vendorExtensions.x-name-lower}}_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + def {{vendorExtensions.x-name-lower}}_with_http_info(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: """ - Asynchronous coroutine to update the {{instanceName}} + Update the {{instanceName}} and return response metadata {{#allParams}} :param {{paramName}}: {{{description}}}{{/allParams}} - :returns: The updated {{instanceName}} + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._{{vendorExtensions.x-name-lower}}({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + instance = {{instanceName}}( + self._version, + payload{{#instancePathParams}}, + {{paramName}}=self._solution['{{paramName}}']{{/instancePathParams}} + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _{{vendorExtensions.x-name-lower}}_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> tuple: + """ + Internal async helper for {{vendorExtensions.x-name-lower}} operation + + Returns: + tuple: (payload, status_code, headers) """ {{#bodyParam}}data = {{paramName}}.to_dict(){{/bodyParam}} {{^bodyParam}}data = values.of({ {{#allParams}}{{#isFormParam}} @@ -88,13 +111,38 @@ class {{apiName}}Context(InstanceContext): {{#allParams}}{{#isQueryParam}}{{#if vendorExtensions.x-prefixed-collapsible-map}}params.update({{vendorExtensions.x-serialize}}({{paramName}}, '{{vendorExtensions.x-prefixed-collapsible-map}}')) {{/if}}{{/isQueryParam}}{{/allParams}}{{/if}} - payload = await self._version.update_async(method='{{vendorExtensions.x-http-method}}', uri=self._uri, data=data, headers=headers{{#if queryParams}}, params=params{{/if}}) + return await self._version.update_with_response_info_async(method='{{vendorExtensions.x-http-method}}', uri=self._uri, data=data, headers=headers{{#if queryParams}}, params=params{{/if}}) + async def {{vendorExtensions.x-name-lower}}_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + """ + Asynchronous coroutine to update the {{instanceName}} + {{#allParams}} + :param {{paramName}}: {{{description}}}{{/allParams}} + + :returns: The updated {{instanceName}} + """ + payload, _, _ = await self._{{vendorExtensions.x-name-lower}}_async({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) return {{instanceName}}( self._version, payload{{#instancePathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/instancePathParams}} ) + + async def {{vendorExtensions.x-name-lower}}_with_http_info_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Asynchronous coroutine to update the {{instanceName}} and return response metadata + {{#allParams}} + :param {{paramName}}: {{{description}}}{{/allParams}} + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._{{vendorExtensions.x-name-lower}}_async({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + instance = {{instanceName}}( + self._version, + payload{{#instancePathParams}}, + {{paramName}}=self._solution['{{paramName}}']{{/instancePathParams}} + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) {{/vendorExtensions.x-twilio.ignoreOperation}}{{/vendorExtensions.x-is-update-operation}}{{#vendorExtensions.x-is-fetch-operation}}{{^vendorExtensions.x-twilio.ignoreOperation}} def {{vendorExtensions.x-name-lower}}(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: """ diff --git a/src/main/resources/twilio-python/instance.handlebars b/src/main/resources/twilio-python/instance.handlebars index 9a2060866..190653fa6 100644 --- a/src/main/resources/twilio-python/instance.handlebars +++ b/src/main/resources/twilio-python/instance.handlebars @@ -49,6 +49,26 @@ class {{instanceName}}(InstanceResource): :returns: The updated {{instanceName}} """ return await self._proxy.update_async({{#allParams}}{{paramName}}={{paramName}}, {{/allParams}}) + + def {{vendorExtensions.x-name-lower}}_with_http_info(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Update the {{instanceName}} with HTTP info + {{#allParams}} + :param {{paramName}}: {{{description}}}{{/allParams}} + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info({{#allParams}}{{paramName}}={{paramName}}, {{/allParams}}) + + async def {{vendorExtensions.x-name-lower}}_with_http_info_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Asynchronous coroutine to update the {{instanceName}} with HTTP info + {{#allParams}} + :param {{paramName}}: {{{description}}}{{/allParams}} + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async({{#allParams}}{{paramName}}={{paramName}}, {{/allParams}}) {{/vendorExtensions.x-is-update-operation}}{{#vendorExtensions.x-is-fetch-operation}} def {{vendorExtensions.x-name-lower}}(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> "{{instanceName}}": """ @@ -69,6 +89,26 @@ class {{instanceName}}(InstanceResource): :returns: The fetched {{instanceName}} """ return await self._proxy.fetch_async({{#allParams}}{{paramName}}={{paramName}}, {{/allParams}}) + + def {{vendorExtensions.x-name-lower}}_with_http_info(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Fetch the {{instanceName}} with HTTP info + {{#allParams}} + :param {{paramName}}: {{{description}}}{{/allParams}} + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info({{#allParams}}{{paramName}}={{paramName}}, {{/allParams}}) + + async def {{vendorExtensions.x-name-lower}}_with_http_info_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Asynchronous coroutine to fetch the {{instanceName}} with HTTP info + {{#allParams}} + :param {{paramName}}: {{{description}}}{{/allParams}} + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async({{#allParams}}{{paramName}}={{paramName}}, {{/allParams}}) {{/vendorExtensions.x-is-fetch-operation}}{{#vendorExtensions.x-is-delete-operation}} def {{vendorExtensions.x-name-lower}}(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> bool: """ @@ -88,6 +128,26 @@ class {{instanceName}}(InstanceResource): :returns: True if delete succeeds, False otherwise """ return await self._proxy.delete_async({{#allParams}}{{paramName}}={{paramName}}, {{/allParams}}) + + def {{vendorExtensions.x-name-lower}}_with_http_info(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Deletes the {{instanceName}} with HTTP info + {{#allParams}} + :param {{paramName}}: {{{description}}}{{/allParams}} + + :returns: ApiResponse with success boolean, status code, and headers + """ + return self._proxy.delete_with_http_info({{#allParams}}{{paramName}}={{paramName}}, {{/allParams}}) + + async def {{vendorExtensions.x-name-lower}}_with_http_info_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Asynchronous coroutine that deletes the {{instanceName}} with HTTP info + {{#allParams}} + :param {{paramName}}: {{{description}}}{{/allParams}} + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_async({{#allParams}}{{paramName}}={{paramName}}, {{/allParams}}) {{/vendorExtensions.x-is-delete-operation}}{{#vendorExtensions.x-is-create-operation}} def {{vendorExtensions.x-name-lower}}(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> "{{instanceName}}": """ @@ -107,6 +167,26 @@ class {{instanceName}}(InstanceResource): :returns: The created {{instanceName}} """ return await self._proxy.create_async({{#allParams}}{{paramName}}{{#if required}}{{else}}={{paramName}}{{/if}}, {{/allParams}}) + + def {{vendorExtensions.x-name-lower}}_with_http_info(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Create the {{instanceName}} with HTTP info + {{#allParams}} + :param {{paramName}}: {{{description}}}{{/allParams}} + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info({{#allParams}}{{paramName}}{{#if required}}{{else}}={{paramName}}{{/if}}, {{/allParams}}) + + async def {{vendorExtensions.x-name-lower}}_with_http_info_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Asynchronous coroutine to create the {{instanceName}} with HTTP info + {{#allParams}} + :param {{paramName}}: {{{description}}}{{/allParams}} + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async({{#allParams}}{{paramName}}{{#if required}}{{else}}={{paramName}}{{/if}}, {{/allParams}}) {{/vendorExtensions.x-is-create-operation}}{{/vendorExtensions.x-is-context-operation}}{{/operations}}{{#dependents}}{{#instanceDependent}} @property def {{mountName}}(self) -> {{listName}}: diff --git a/src/main/resources/twilio-python/listOperations.handlebars b/src/main/resources/twilio-python/listOperations.handlebars index 9ac8e5ebc..065068784 100644 --- a/src/main/resources/twilio-python/listOperations.handlebars +++ b/src/main/resources/twilio-python/listOperations.handlebars @@ -1,12 +1,11 @@ {{#operations}} {{#vendorExtensions.x-is-create-operation}} - def create(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + def _create(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> tuple: """ - Create the {{instanceName}} + Internal helper for create operation - {{#allParams}}:param {{paramName}}: {{{description}}} - {{/allParams}} - :returns: The created {{instanceName}} + Returns: + tuple: (payload, status_code, headers) """ {{#bodyParam}}data = {{paramName}}.to_dict(){{/bodyParam}} {{^bodyParam}}{{#hasParams}}data = values.of({ {{#allParams}}{{#isFormParam}} @@ -27,17 +26,37 @@ {{/queryParams}} }) {{/queryParams.0}} - payload = self._version.create(method='{{vendorExtensions.x-http-method}}', uri=self._uri, {{#hasParams}}data=data,{{/hasParams}} headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) + return self._version.create_with_response_info(method='{{vendorExtensions.x-http-method}}', uri=self._uri, {{#hasParams}}data=data,{{/hasParams}} headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) + + def create(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + """ + Create the {{instanceName}} + {{#allParams}}:param {{paramName}}: {{{description}}} + {{/allParams}} + :returns: The created {{instanceName}} + """ + payload, _, _ = self._create({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) return {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}) - async def create_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + def create_with_http_info(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: """ - Asynchronously create the {{instanceName}} + Create the {{instanceName}} and return response metadata {{#allParams}}:param {{paramName}}: {{{description}}} {{/allParams}} - :returns: The created {{instanceName}} + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + instance = {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ {{#bodyParam}}data = {{paramName}}.to_dict(){{/bodyParam}} {{^bodyParam}}{{#hasParams}}data = values.of({ {{#allParams}}{{#isFormParam}} @@ -58,16 +77,37 @@ {{/queryParams}} }) {{/queryParams.0}} - payload = await self._version.create_async(method='{{vendorExtensions.x-http-method}}', uri=self._uri, {{#hasParams}}data=data,{{/hasParams}} headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) + return await self._version.create_with_response_info_async(method='{{vendorExtensions.x-http-method}}', uri=self._uri, {{#hasParams}}data=data,{{/hasParams}} headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) + async def create_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + """ + Asynchronously create the {{instanceName}} + + {{#allParams}}:param {{paramName}}: {{{description}}} + {{/allParams}} + :returns: The created {{instanceName}} + """ + payload, _, _ = await self._create_async({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) return {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}) + + async def create_with_http_info_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Asynchronously create the {{instanceName}} and return response metadata + + {{#allParams}}:param {{paramName}}: {{{description}}} + {{/allParams}} + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + instance = {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}) + return ApiResponse(data=instance, status_code=status_code, headers=headers) {{/vendorExtensions.x-is-create-operation}}{{^instancePath}}{{#vendorExtensions.x-is-fetch-operation}} - def fetch(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + def _fetch(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> tuple: """ - Asynchronously fetch the {{instanceName}} + Internal helper for fetch operation - {{#allParams}}:param {{paramName}}: {{{description}}}{{/allParams}} - :returns: The fetched {{instanceName}} + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({ {{#headerParams}}'{{{baseName}}}': {{paramName}}, @@ -84,16 +124,35 @@ {{/queryParams}} }) {{/queryParams.0}} - payload = self._version.fetch(method='{{vendorExtensions.x-http-method}}', uri=self._uri, headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) + return self._version.fetch_with_response_info(method='{{vendorExtensions.x-http-method}}', uri=self._uri, headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) + def fetch(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + """ + Fetch the {{instanceName}} + + {{#allParams}}:param {{paramName}}: {{{description}}}{{/allParams}} + :returns: The fetched {{instanceName}} + """ + payload, _, _ = self._fetch({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) return {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}) - async def fetch_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + def fetch_with_http_info(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: """ - Asynchronously fetch the {{instanceName}} + Fetch the {{instanceName}} and return response metadata {{#allParams}}:param {{paramName}}: {{{description}}}{{/allParams}} - :returns: The fetched {{instanceName}} + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + instance = {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _fetch_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) """ headers = values.of({ {{#headerParams}}'{{{baseName}}}': {{paramName}}, @@ -110,15 +169,34 @@ {{/queryParams}} }) {{/queryParams.0}} - payload = await self._version.fetch_async(method='{{vendorExtensions.x-http-method}}', uri=self._uri, headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) + return await self._version.fetch_with_response_info_async(method='{{vendorExtensions.x-http-method}}', uri=self._uri, headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) - return {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}){{/vendorExtensions.x-is-fetch-operation}}{{#vendorExtensions.x-is-delete-operation}} - def delete(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> bool: + async def fetch_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: """ - Asynchronously delete the {{instanceName}} + Asynchronously fetch the {{instanceName}} {{#allParams}}:param {{paramName}}: {{{description}}}{{/allParams}} - :returns: True if delete succeeds, False otherwise + :returns: The fetched {{instanceName}} + """ + payload, _, _ = await self._fetch_async({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + return {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}) + + async def fetch_with_http_info_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Asynchronously fetch the {{instanceName}} and return response metadata + + {{#allParams}}:param {{paramName}}: {{{description}}}{{/allParams}} + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + instance = {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}) + return ApiResponse(data=instance, status_code=status_code, headers=headers){{/vendorExtensions.x-is-fetch-operation}}{{#vendorExtensions.x-is-delete-operation}} + def _delete(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) """ headers = values.of({ {{#headerParams}}'{{{baseName}}}': {{paramName}}, @@ -134,15 +212,35 @@ {{#queryParams}}'{{{baseName}}}': {{paramName}}, {{/queryParams}} }){{/queryParams.0}} - return self._version.delete(method='{{vendorExtensions.x-http-method}}', uri=self._uri, headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) + return self._version.delete_with_response_info(method='{{vendorExtensions.x-http-method}}', uri=self._uri, headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) - async def delete_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> bool: + def delete(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> bool: """ - Asynchronously delete the {{instanceName}} + Delete the {{instanceName}} {{#allParams}}:param {{paramName}}: {{{description}}}{{/allParams}} :returns: True if delete succeeds, False otherwise """ + success, _, _ = self._delete({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + return success + + def delete_with_http_info(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Delete the {{instanceName}} and return response metadata + + {{#allParams}}:param {{paramName}}: {{{description}}}{{/allParams}} + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = self._delete({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + async def _delete_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> tuple: + """ + Internal async helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ headers = values.of({ {{#headerParams}}'{{{baseName}}}': {{paramName}}, {{/headerParams}}'Content-Type': 'application/x-www-form-urlencoded' @@ -157,15 +255,34 @@ {{#queryParams}}'{{{baseName}}}': {{paramName}}, {{/queryParams}} }){{/queryParams.0}} - return await self._version.delete_async(method='{{vendorExtensions.x-http-method}}', uri=self._uri, headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}){{/vendorExtensions.x-is-delete-operation}}{{#vendorExtensions.x-is-update-operation}} + return await self._version.delete_with_response_info_async(method='{{vendorExtensions.x-http-method}}', uri=self._uri, headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) - def update(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + async def delete_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> bool: """ - Update the {{instanceName}} + Asynchronously delete the {{instanceName}} - {{#allParams}}:param {{paramName}}: {{{description}}} - {{/allParams}} - :returns: The created {{instanceName}} + {{#allParams}}:param {{paramName}}: {{{description}}}{{/allParams}} + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = await self._delete_async({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + return success + + async def delete_with_http_info_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Asynchronously delete the {{instanceName}} and return response metadata + + {{#allParams}}:param {{paramName}}: {{{description}}}{{/allParams}} + :returns: ApiResponse with success boolean, status code, and headers + """ + success, status_code, headers = await self._delete_async({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + return ApiResponse(data=success, status_code=status_code, headers=headers){{/vendorExtensions.x-is-delete-operation}}{{#vendorExtensions.x-is-update-operation}} + + def _update(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ {{#bodyParam}}data = {{paramName}}.to_dict(){{/bodyParam}} {{^bodyParam}}{{#hasParams}}data = values.of({ {{#allParams}}{{#isFormParam}} @@ -186,17 +303,37 @@ {{/queryParams}} }) {{/queryParams.0}} - payload = self._version.update(method='{{vendorExtensions.x-http-method}}', uri=self._uri, {{#hasParams}}data=data,{{/hasParams}} headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) + return self._version.update_with_response_info(method='{{vendorExtensions.x-http-method}}', uri=self._uri, {{#hasParams}}data=data,{{/hasParams}} headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) + + def update(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + """ + Update the {{instanceName}} + {{#allParams}}:param {{paramName}}: {{{description}}} + {{/allParams}} + :returns: The updated {{instanceName}} + """ + payload, _, _ = self._update({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) return {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}) - async def update_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + def update_with_http_info(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: """ - Asynchronously update the {{instanceName}} + Update the {{instanceName}} and return response metadata {{#allParams}}:param {{paramName}}: {{{description}}} {{/allParams}} - :returns: The created {{instanceName}} + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + instance = {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) """ {{#bodyParam}}data = {{paramName}}.to_dict(){{/bodyParam}} {{^bodyParam}}{{#hasParams}}data = values.of({ {{#allParams}}{{#isFormParam}} @@ -217,9 +354,30 @@ {{/queryParams}} }) {{/queryParams.0}} - payload = await self._version.update_async(method='{{vendorExtensions.x-http-method}}', uri=self._uri, {{#hasParams}}data=data,{{/hasParams}} headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) + return await self._version.update_with_response_info_async(method='{{vendorExtensions.x-http-method}}', uri=self._uri, {{#hasParams}}data=data,{{/hasParams}} headers=headers{{#queryParams.0}}, params=params{{/queryParams.0}}) + + async def update_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> {{instanceName}}: + """ + Asynchronously update the {{instanceName}} + + {{#allParams}}:param {{paramName}}: {{{description}}} + {{/allParams}} + :returns: The updated {{instanceName}} + """ + payload, _, _ = await self._update_async({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + return {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}) - return {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}){{/vendorExtensions.x-is-update-operation}}{{/instancePath}}{{#vendorExtensions.x-is-read-operation}} + async def update_with_http_info_async(self{{#allParams}}, {{paramName}}: {{#if required}}{{{dataType}}}{{else}}Union[{{{dataType}}}, object]=values.unset{{/if}}{{/allParams}}) -> ApiResponse: + """ + Asynchronously update the {{instanceName}} and return response metadata + + {{#allParams}}:param {{paramName}}: {{{description}}} + {{/allParams}} + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async({{#allParams}}{{paramName}}={{paramName}}{{#unless @last}}, {{/unless}}{{/allParams}}) + instance = {{instanceName}}(self._version, payload{{#listPathParams}}, {{paramName}}=self._solution['{{paramName}}']{{/listPathParams}}) + return ApiResponse(data=instance, status_code=status_code, headers=headers){{/vendorExtensions.x-is-update-operation}}{{/instancePath}}{{#vendorExtensions.x-is-read-operation}} def stream(self, {{#allParams}} {{#startsWith paramName text='page_size'}}{{else}}{{paramName}}: Union[{{{dataType}}}, object] = values.unset,{{/startsWith}}{{/allParams}} limit: Optional[int] = None, @@ -278,6 +436,62 @@ return self._version.stream_async(page, limits['limit']) + def stream_with_http_info(self, {{#allParams}} + {{#startsWith paramName text='page_size'}}{{else}}{{paramName}}: Union[{{{dataType}}}, object] = values.unset,{{/startsWith}}{{/allParams}} + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams {{instanceName}} and returns headers from first page + + {{#allParams}}{{#startsWith paramName text='page_size'}}{{else}} + :param {{dataType}} {{paramName}}: {{{description}}}{{/startsWith}}{{/allParams}} + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info({{#allParams}}{{#startsWith paramName text='page_size'}}{{else}} + {{paramName}}={{paramName}},{{/startsWith}}{{/allParams}} + page_size=limits['page_size'] + ) + + generator = self._version.stream(page_response.data, limits['limit']) + return (generator, page_response.status_code, page_response.headers) + + async def stream_with_http_info_async(self, {{#allParams}} + {{#startsWith paramName text='page_size'}}{{else}}{{paramName}}: Union[{{{dataType}}}, object] = values.unset,{{/startsWith}}{{/allParams}} + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams {{instanceName}} and returns headers from first page + + {{#allParams}}{{#startsWith paramName text='page_size'}}{{else}} + :param {{dataType}} {{paramName}}: {{{description}}}{{/startsWith}}{{/allParams}} + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async({{#allParams}}{{#startsWith paramName text='page_size'}}{{else}} + {{paramName}}={{paramName}},{{/startsWith}}{{/allParams}} + page_size=limits['page_size'] + ) + + generator = self._version.stream_async(page_response.data, limits['limit']) + return (generator, page_response.status_code, page_response.headers) + def list(self, {{#allParams}} {{#startsWith paramName text='page_size'}}{{else}}{{paramName}}: Union[{{{dataType}}}, object] = values.unset,{{/startsWith}}{{/allParams}} limit: Optional[int] = None, @@ -330,8 +544,62 @@ page_size=page_size, )] - def page(self, {{#allParams}} + def list_with_http_info(self, {{#allParams}} + {{#startsWith paramName text='page_size'}}{{else}}{{paramName}}: Union[{{{dataType}}}, object] = values.unset,{{/startsWith}}{{/allParams}} + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists {{instanceName}} and returns headers from first page + + {{#allParams}}{{#startsWith paramName text='page_size'}}{{else}} + :param {{dataType}} {{paramName}}: {{{description}}}{{/startsWith}}{{/allParams}} + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + {{#allParams}}{{#startsWith paramName text='page_size'}}{{else}}{{paramName}}={{paramName}}, + {{/startsWith}}{{/allParams}}limit=limit, + page_size=page_size, + ) + items = list(generator) + return ApiResponse(data=items, status_code=status_code, headers=headers) + + async def list_with_http_info_async(self, {{#allParams}} {{#startsWith paramName text='page_size'}}{{else}}{{paramName}}: Union[{{{dataType}}}, object] = values.unset,{{/startsWith}}{{/allParams}} + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists {{instanceName}} and returns headers from first page + + {{#allParams}}{{#startsWith paramName text='page_size'}}{{else}} + :param {{dataType}} {{paramName}}: {{{description}}}{{/startsWith}}{{/allParams}} + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + {{#allParams}}{{#startsWith paramName text='page_size'}}{{else}}{{paramName}}={{paramName}}, + {{/startsWith}}{{/allParams}}limit=limit, + page_size=page_size, + ) + items = [record async for record in generator] + return ApiResponse(data=items, status_code=status_code, headers=headers) + + def page(self, {{#allParams}} + {{#startsWith paramName text='page_size'}}{{else}}{{#startsWith paramName text='page_token'}}{{else}}{{paramName}}: Union[{{{dataType}}}, object] = values.unset,{{/startsWith}}{{/startsWith}}{{/allParams}} page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -365,8 +633,9 @@ headers["Accept"] = "{{{mediaType}}}" {{/vendorExtensions.successProduce}} - response = self._version.page(method='{{vendorExtensions.x-http-method}}', uri=self._uri, params=data, headers=headers) - return {{apiName}}Page(self._version, response{{#if listPathParams}}, self._solution{{/if}}) + response = self._version.page(method='{{vendorExtensions.x-http-method}}', uri=self._uri, params=data, headers=headers){{#isApiV1}} + return {{apiName}}Page(self._version, response, uri=self._uri{{#if listPathParams}}, self._solution{{/if}}){{/isApiV1}}{{^isApiV1}} + return {{apiName}}Page(self._version, response{{#if listPathParams}}, self._solution{{/if}}){{/isApiV1}} async def page_async(self, {{#allParams}} {{#startsWith paramName text='page_size'}}{{else}}{{paramName}}: Union[{{{dataType}}}, object] = values.unset,{{/startsWith}}{{/allParams}} @@ -406,6 +675,85 @@ response = await self._version.page_async(method='{{vendorExtensions.x-http-method}}', uri=self._uri, params=data, headers=headers) return {{apiName}}Page(self._version, response{{#if listPathParams}}, self._solution{{/if}}) + def page_with_http_info(self, {{#allParams}} + {{#startsWith paramName text='page_size'}}{{else}}{{#startsWith paramName text='page_token'}}{{else}}{{paramName}}: Union[{{{dataType}}}, object] = values.unset,{{/startsWith}}{{/startsWith}}{{/allParams}} + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + {{#allParams}}{{#startsWith paramName text='page_size'}}{{else}} + :param {{paramName}}: {{{description}}}{{/startsWith}}{{/allParams}} + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with {{apiName}}Page, status code, and headers + """ + data = values.of({ {{#allParams}}{{#startsWith paramName text='page_size'}}{{else}} + '{{{baseName}}}': {{#if vendorExtensions.x-serialize}}{{vendorExtensions.x-serialize}}({{paramName}}{{#if isArray}}, lambda e: e){{else}}){{/if}}{{else}}{{paramName}}{{/if}},{{/startsWith}}{{/allParams}} + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + {{#headerParams}}'{{{baseName}}}': {{paramName}}, + {{/headerParams}}'Content-Type': 'application/x-www-form-urlencoded' + }) + {{#consumes}} + headers["Content-Type"] = "{{{mediaType}}}" + {{/consumes}} + {{#vendorExtensions.successProduce}} + headers["Accept"] = "{{{mediaType}}}" + {{/vendorExtensions.successProduce}} + + response, status_code, response_headers = self._version.page_with_response_info(method='{{vendorExtensions.x-http-method}}', uri=self._uri, params=data, headers=headers){{#isApiV1}} + page = {{apiName}}Page(self._version, response, uri=self._uri{{#if listPathParams}}, self._solution{{/if}}){{/isApiV1}}{{^isApiV1}} + page = {{apiName}}Page(self._version, response{{#if listPathParams}}, self._solution{{/if}}){{/isApiV1}} + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_async(self, {{#allParams}} + {{#startsWith paramName text='page_size'}}{{else}}{{paramName}}: Union[{{{dataType}}}, object] = values.unset,{{/startsWith}}{{/allParams}} + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + {{#allParams}}{{#startsWith paramName text='page_size'}}{{else}} + :param {{paramName}}: {{{description}}}{{/startsWith}}{{/allParams}} + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: ApiResponse with {{apiName}}Page, status code, and headers + """ + data = values.of({ {{#allParams}}{{#startsWith paramName text='page_size'}}{{else}} + '{{{baseName}}}': {{#if vendorExtensions.x-serialize}}{{vendorExtensions.x-serialize}}({{paramName}}{{#if isArray}}, lambda e: e){{else}}){{/if}}{{else}}{{paramName}}{{/if}},{{/startsWith}}{{/allParams}} + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + {{#headerParams}}'{{{baseName}}}': {{paramName}}, + {{/headerParams}}'Content-Type': 'application/x-www-form-urlencoded' + }) + {{#consumes}} + headers["Content-Type"] = "{{{mediaType}}}" + {{/consumes}} + {{#produces}} + headers["Accept"] = "{{{mediaType}}}" + {{/produces}} + + response, status_code, response_headers = await self._version.page_with_response_info_async(method='{{vendorExtensions.x-http-method}}', uri=self._uri, params=data, headers=headers) + page = {{apiName}}Page(self._version, response{{#if listPathParams}}, self._solution{{/if}}) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + def get_page(self, target_url: str) -> {{apiName}}Page: """ Retrieve a specific page of {{instanceName}} records from the API. diff --git a/src/main/resources/twilio-python/pagination.handlebars b/src/main/resources/twilio-python/pagination.handlebars index fed914e4a..e18993965 100644 --- a/src/main/resources/twilio-python/pagination.handlebars +++ b/src/main/resources/twilio-python/pagination.handlebars @@ -1,6 +1,6 @@ {{#operations}} {{#vendorExtensions.x-is-read-operation}} -class {{apiName}}Page(Page): +class {{apiName}}Page({{#isApiV1}}TokenPagination{{/isApiV1}}{{^isApiV1}}Page{{/isApiV1}}): def get_instance(self, payload: Dict[str, Any]) -> {{instanceName}}: """ diff --git a/src/main/resources/twilio-ruby/api.mustache b/src/main/resources/twilio-ruby/api.mustache index 3379a54a7..3a6ad4b2e 100644 --- a/src/main/resources/twilio-ruby/api.mustache +++ b/src/main/resources/twilio-ruby/api.mustache @@ -14,6 +14,7 @@ module Twilio {{>context}} {{/metaProperties.hasInstanceOperation}} {{>page}} +{{>pageMetadata}} {{>instance}} end end diff --git a/src/main/resources/twilio-ruby/context.mustache b/src/main/resources/twilio-ruby/context.mustache index f22809571..055ea9a0d 100644 --- a/src/main/resources/twilio-ruby/context.mustache +++ b/src/main/resources/twilio-ruby/context.mustache @@ -12,7 +12,9 @@ {{/instancePathParams}} # @return [{{apiName}}Context] {{apiName}}Context def initialize(version{{#instancePathParams}}, {{paramName}}{{/instancePathParams}}) - super(version) + {{^isApiV1}}super(version){{/isApiV1}} + {{#isApiV1}}apiV1Version = ApiV1Version.new version.domain, version + super(apiV1Version){{/isApiV1}} # Path Solution @solution = { {{#instancePathParams}}{{paramName}}: {{paramName}}, {{/instancePathParams}} } @@ -32,6 +34,8 @@ {{#vendorExtensions.instanceOperation}} {{>methods}} {{>contextMethodParams}} +{{>methodsMetadata}} +{{>contextMethodParamsMetadata}} {{/vendorExtensions.instanceOperation}} {{/apiOperations}} {{#metaProperties.contextImportProperties}} @@ -94,3 +98,50 @@ "#" end end + + class {{apiName}}InstanceMetadata < InstanceResourceMetadata + ## + # Initializes a new {{apiName}}InstanceMetadata. + # @param [Version] version Version that contains the resource + # @param [}{{apiName}}Instance] {{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}}_instance The instance associated with the metadata. + # @param [Hash] headers Header object with response headers. + # @param [Integer] status_code The HTTP status code of the response. + # @return [{{apiName}}InstanceMetadata] The initialized instance with metadata. + def initialize(version, {{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}}_instance, headers, status_code) + super(version, headers, status_code) + @{{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}}_instance = {{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}}_instance + end + + def {{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}} + @{{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}}_instance + end + + def headers + @headers + end + + def status_code + @status_code + end + + def to_s + "" + end + end + + class {{apiName}}ListResponse < InstanceListResource + # @param [Array<{{apiName}}Instance>] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @{{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}}_instance = payload.body[key].map do |data| + {{apiName}}Instance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def {{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}}_instance + @instance + end + end diff --git a/src/main/resources/twilio-ruby/contextMethodParams.mustache b/src/main/resources/twilio-ruby/contextMethodParams.mustache index d08400293..0fd4cf1bd 100644 --- a/src/main/resources/twilio-ruby/contextMethodParams.mustache +++ b/src/main/resources/twilio-ruby/contextMethodParams.mustache @@ -116,6 +116,15 @@ ) {{/vendorExtensions.x-is-delete-operation}} {{#vendorExtensions.x-is-delete-operation}} - @version.{{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}('{{httpMethod}}', @uri{{#queryParams.0}}, params: params{{/queryParams.0}}{{#formParams.0}}, data: data{{/formParams.0}}, headers: headers) + {{#isApiV1}} + response = @version.delete_with_metadata('{{httpMethod}}', @uri{{#queryParams.0}}, params: params{{/queryParams.0}}{{#formParams.0}}, data: data{{/formParams.0}}, headers: headers{{#bodyParams.0}}, data: {{paramName}}.to_json{{/bodyParams.0}}) + {{apiName}}Instance.new( + @version, + response.body,{{#vendorExtensions.listOperation}}{{#listPathParams}} + {{paramName}}: @solution[:{{paramName}}],{{/listPathParams}}{{/vendorExtensions.listOperation}}{{#vendorExtensions.instanceOperation}}{{#instancePathParams}} + {{paramName}}: @solution[:{{paramName}}],{{/instancePathParams}}{{/vendorExtensions.instanceOperation}} + ) + {{/isApiV1}}{{^isApiV1}} + @version.{{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}('{{httpMethod}}', @uri{{#queryParams.0}}, params: params{{/queryParams.0}}{{#formParams.0}}, data: data{{/formParams.0}}, headers: headers){{/isApiV1}} {{/vendorExtensions.x-is-delete-operation}} end diff --git a/src/main/resources/twilio-ruby/contextMethodParamsMetadata.mustache b/src/main/resources/twilio-ruby/contextMethodParamsMetadata.mustache new file mode 100644 index 000000000..aa997b8a1 --- /dev/null +++ b/src/main/resources/twilio-ruby/contextMethodParamsMetadata.mustache @@ -0,0 +1,134 @@ + {{#queryParams.0}} + params = Twilio::Values.of({ + {{#queryParams}} + {{#required}} + {{^vendorExtensions.x-prefixed-collapsible-map}} + {{^vendorExtensions.x-serialize}} + '{{baseName}}' => {{paramName}}, + {{/vendorExtensions.x-serialize}} + {{#vendorExtensions.x-serialize}} + {{^isArray}} + '{{baseName}}' => {{vendorExtensions.x-serialize}}({{paramName}}), + {{/isArray}} + {{#isArray}} + '{{baseName}}' => {{vendorExtensions.x-serialize}}({{paramName}}) { |e| {{^vendorExtensions.x-is-array-of-objects}}e{{/vendorExtensions.x-is-array-of-objects}}{{#vendorExtensions.x-is-array-of-objects}}{{.}}{{/vendorExtensions.x-is-array-of-objects}} }, + {{/isArray}} + {{/vendorExtensions.x-serialize}} + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/required}} + {{/queryParams}} + {{#queryParams}} + {{^required}} + {{^vendorExtensions.x-prefixed-collapsible-map}} + {{^vendorExtensions.x-serialize}} + '{{baseName}}' => {{paramName}}, + {{/vendorExtensions.x-serialize}} + {{#vendorExtensions.x-serialize}} + {{^isArray}} + '{{baseName}}' => {{vendorExtensions.x-serialize}}({{paramName}}), + {{/isArray}} + {{#isArray}} + '{{baseName}}' => {{vendorExtensions.x-serialize}}({{paramName}}) { |e| {{^vendorExtensions.x-is-array-of-objects}}e{{/vendorExtensions.x-is-array-of-objects}}{{#vendorExtensions.x-is-array-of-objects}}{{.}}{{/vendorExtensions.x-is-array-of-objects}} }, + {{/isArray}} + {{/vendorExtensions.x-serialize}} + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/required}} + {{/queryParams}} + }) + {{#queryParams}} + {{#required}} + {{#vendorExtensions.x-prefixed-collapsible-map}} + params.merge!(Twilio.prefixed_collapsible_map({{paramName}}, 'AddOns')) + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/required}} + {{/queryParams}} + {{#queryParams}} + {{^required}} + {{#vendorExtensions.x-prefixed-collapsible-map}} + params.merge!(Twilio.prefixed_collapsible_map({{paramName}}, 'AddOns')) + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/required}} + {{/queryParams}} + {{/queryParams.0}} + {{#formParams.0}} + data = Twilio::Values.of({ + {{#requiredParams}} + {{#isFormParam}} + {{^vendorExtensions.x-prefixed-collapsible-map}} + {{^vendorExtensions.x-serialize}} + '{{baseName}}' => {{paramName}}, + {{/vendorExtensions.x-serialize}} + {{#vendorExtensions.x-serialize}} + {{^isArray}} + '{{baseName}}' => {{vendorExtensions.x-serialize}}({{paramName}}), + {{/isArray}} + {{#isArray}} + '{{baseName}}' => {{vendorExtensions.x-serialize}}({{paramName}}) { |e| {{^vendorExtensions.x-is-array-of-objects}}e{{/vendorExtensions.x-is-array-of-objects}}{{#vendorExtensions.x-is-array-of-objects}}{{.}}{{/vendorExtensions.x-is-array-of-objects}} }, + {{/isArray}} + {{/vendorExtensions.x-serialize}} + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/isFormParam}} + {{/requiredParams}} + {{#optionalParams}} + {{#isFormParam}} + {{^vendorExtensions.x-prefixed-collapsible-map}} + {{^vendorExtensions.x-serialize}} + '{{baseName}}' => {{paramName}}, + {{/vendorExtensions.x-serialize}} + {{#vendorExtensions.x-serialize}} + {{^isArray}} + '{{baseName}}' => {{vendorExtensions.x-serialize}}({{paramName}}), + {{/isArray}} + {{#isArray}} + '{{baseName}}' => {{vendorExtensions.x-serialize}}({{paramName}}) { |e| {{^vendorExtensions.x-is-array-of-objects}}e{{/vendorExtensions.x-is-array-of-objects}}{{#vendorExtensions.x-is-array-of-objects}}{{.}}{{/vendorExtensions.x-is-array-of-objects}} }, + {{/isArray}} + {{/vendorExtensions.x-serialize}} + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/isFormParam}} + {{/optionalParams}} + }) + {{#requiredParams}} + {{#isFormParam}} + {{#vendorExtensions.x-prefixed-collapsible-map}} + data.merge!(Twilio.prefixed_collapsible_map({{paramName}}, 'AddOns')) + {{/vendorExtensions.x-prefixed-collapsible-map}} + {{/isFormParam}} + {{/requiredParams}} + {{#optionalParams}} + {{#isFormParam}} + {{#vendorExtensions.x-prefixed-collapsible-map}} + data.merge!(Twilio.prefixed_collapsible_map({{paramName}}, 'AddOns')) + {{/vendorExtensions.x-prefixed-collapsible-map}}{{/isFormParam}}{{/optionalParams}} + {{/formParams.0}} + headers = Twilio::Values.of({'Content-Type' => 'application/x-www-form-urlencoded', {{#headerParams}}{{#required}}'{{baseName}}' => {{paramName}}, {{/required}}{{/headerParams}}{{#headerParams}}{{^required}}'{{baseName}}' => {{paramName}}, {{/required}}{{/headerParams}}}) + {{^vendorExtensions.scimConsumes}}{{#bodyParams.0}}headers['Content-Type'] = 'application/json'{{/bodyParams.0}}{{/vendorExtensions.scimConsumes}} + {{#vendorExtensions.scimConsumes}}headers['Content-Type'] = 'application/scim+json'{{/vendorExtensions.scimConsumes}} + {{#vendorExtensions.x-is-delete-operation}}{{#vendorExtensions.scimProduces}}headers['Accept'] = '*/*'{{/vendorExtensions.scimProduces}}{{/vendorExtensions.x-is-delete-operation}} + {{^vendorExtensions.x-is-delete-operation}} + {{#vendorExtensions.scimProduces}}headers['Accept'] = 'application/scim+json'{{/vendorExtensions.scimProduces}} + {{#vendorExtensions.multipleProduces}} headers['Accept'] = '*/*'{{/vendorExtensions.multipleProduces}} + response = @version.{{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}_with_metadata('{{httpMethod}}', @uri{{#queryParams.0}}, params: params{{/queryParams.0}}{{#formParams.0}}, data: data{{/formParams.0}}, headers: headers{{#bodyParams.0}}, data: {{paramName}}.to_json{{/bodyParams.0}}) + {{#lambda.camelcase}}{{apiName}}{{/lambda.camelcase}}_instance = {{apiName}}Instance.new( + @version, + response.body,{{#vendorExtensions.listOperation}}{{#listPathParams}} + {{paramName}}: @solution[:{{paramName}}],{{/listPathParams}}{{/vendorExtensions.listOperation}}{{#vendorExtensions.instanceOperation}}{{#instancePathParams}} + {{paramName}}: @solution[:{{paramName}}],{{/instancePathParams}}{{/vendorExtensions.instanceOperation}} + ) + {{apiName}}InstanceMetadata.new( + @version, + {{#lambda.camelcase}}{{apiName}}{{/lambda.camelcase}}_instance, + response.headers, + response.status_code + ) + {{/vendorExtensions.x-is-delete-operation}} + {{#vendorExtensions.x-is-delete-operation}} + response = @version.{{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}_with_metadata('{{httpMethod}}', @uri{{#queryParams.0}}, params: params{{/queryParams.0}}{{#formParams.0}}, data: data{{/formParams.0}}, headers: headers) + {{#lambda.camelcase}}{{apiName}}{{/lambda.camelcase}}_instance = {{apiName}}Instance.new( + @version, + response.body, + account_sid: @solution[:account_sid], + sid: @solution[:sid], + ) + {{apiName}}InstanceMetadata.new(@version, {{#lambda.camelcase}}{{apiName}}{{/lambda.camelcase}}_instance, response.headers, response.status_code) + {{/vendorExtensions.x-is-delete-operation}} + end diff --git a/src/main/resources/twilio-ruby/instance.mustache b/src/main/resources/twilio-ruby/instance.mustache index 8d6a54181..55aff4adc 100644 --- a/src/main/resources/twilio-ruby/instance.mustache +++ b/src/main/resources/twilio-ruby/instance.mustache @@ -9,7 +9,9 @@ # @param [String] sid The SID of the Call resource to fetch. # @return [{{apiName}}Instance] {{apiName}}Instance def initialize(version{{#responseModel}}{{#hasVars}}, payload{{/hasVars}}{{/responseModel}} {{#requiredPathParams}}, {{paramName}}: nil{{/requiredPathParams}}) - super(version) + {{^isApiV1}}super(version){{/isApiV1}} + {{#isApiV1}}apiV1Version = ApiV1Version.new version.domain, version + super(apiV1Version){{/isApiV1}} {{#responseModel}}{{#hasVars}} # Marshaled Properties @properties = { {{/hasVars}}{{/responseModel}}{{#responseModel}}{{#vars}} diff --git a/src/main/resources/twilio-ruby/list.mustache b/src/main/resources/twilio-ruby/list.mustache index 6a208c26c..b136a9fa6 100644 --- a/src/main/resources/twilio-ruby/list.mustache +++ b/src/main/resources/twilio-ruby/list.mustache @@ -5,7 +5,9 @@ # @param [Version] version Version that contains the resource # @return [{{apiName}}List] {{apiName}}List def initialize(version{{#listPathParams}}, {{paramName}}: nil{{/listPathParams}}) - super(version) + {{^isApiV1}}super(version){{/isApiV1}} + {{#isApiV1}}apiV1Version = ApiV1Version.new version.domain, version + super(apiV1Version){{/isApiV1}} # Path Solution @solution = { {{#listPathParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/listPathParams}} } {{#listPath}}@uri = "{{listPath}}"{{/listPath}} @@ -22,6 +24,8 @@ {{^vendorExtensions.x-is-read-operation}} {{>methods}} {{>contextMethodParams}} +{{>methodsMetadata}} +{{>contextMethodParamsMetadata}} {{/vendorExtensions.x-is-read-operation}} {{/vendorExtensions.listOperation}} {{/apiOperations}} @@ -76,6 +80,34 @@ @version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit]) end + ## + # Lists {{apiName}}PageMetadata records from the API as a list. + {{#readParams}} + # @param [{{dataType}}] {{paramName}} {{{description}}} + {{/readParams}} + # @param [Integer] limit Upper limit for the number of records to return. stream() + # guarantees to never return more than limit. Default is no limit + # @param [Integer] page_size Number of records to fetch per request, when + # not set will use the default value of 50 records. If no page_size is defined + # but a limit is defined, stream() will attempt to read the limit with the most + # efficient page size, i.e. min(limit, 1000) + # @return [Array] Array of up to limit results + def list_with_metadata({{#readParams.0}}{{#readParams}}{{>params}}{{/readParams}}, {{/readParams.0}}limit: nil, page_size: nil) + limits = @version.read_limits(limit, page_size) + params = Twilio::Values.of({ + {{#readParams}}{{^vendorExtensions.x-serialize}}'{{{baseName}}}' => {{paramName}}, + {{/vendorExtensions.x-serialize}}{{#vendorExtensions.x-serialize}}{{^vendorExtensions.isList}}'{{{baseName}}}' => {{vendorExtensions.x-serialize}}({{paramName}}),{{/vendorExtensions.isList}} + {{#vendorExtensions.isList}}'{{{baseName}}}' => {{vendorExtensions.x-serialize}}({{paramName}}) { |e| e }, + {{/vendorExtensions.isList}}{{/vendorExtensions.x-serialize}}{{/readParams}} + 'PageSize' => page_size, + }); + headers = Twilio::Values.of({}) + + response = @version.page('GET', @uri, params: params, headers: headers) + + {{apiName}}PageMetadata.new(@version, response, @solution, limits[:limit]) + end + ## # When passed a block, yields {{apiName}}Instance records from the API. # This operation lazily loads records as efficiently as possible until the limit @@ -96,17 +128,18 @@ {{#readParams}} # @param [{{dataType}}] {{paramName}} {{{description}}} {{/readParams}} - # @param [String] page_token PageToken provided by the API + {{^isApiV1}}# @param [String] page_token PageToken provided by the API # @param [Integer] page_number Page Number, this value is simply for client state - # @param [Integer] page_size Number of records to return, defaults to 50 + # @param [Integer] page_size Number of records to return, defaults to 50{{/isApiV1}} # @return [Page] Page of {{apiName}}Instance - def page({{#readParams.0}}{{#readParams}}{{>params}}{{/readParams}}, {{/readParams.0}}page_token: :unset, page_number: :unset, page_size: :unset) + def page({{#readParams.0}}{{#readParams}}{{>params}}{{/readParams}}, {{/readParams.0}}{{^isApiV1}}page_token: :unset, page_number: :unset,{{/isApiV1}}page_size: :unset) params = Twilio::Values.of({ {{#readParams}}{{^vendorExtensions.x-serialize}}'{{{baseName}}}' => {{paramName}}, {{/vendorExtensions.x-serialize}}{{#vendorExtensions.x-serialize}}{{^vendorExtensions.isList}}'{{{baseName}}}' => {{vendorExtensions.x-serialize}}({{paramName}}),{{/vendorExtensions.isList}} {{#vendorExtensions.isList}}'{{{baseName}}}' => {{vendorExtensions.x-serialize}}({{paramName}}) { |e| e }, - {{/vendorExtensions.isList}}{{/vendorExtensions.x-serialize}}{{/readParams}}'PageToken' => page_token, + {{/vendorExtensions.isList}}{{/vendorExtensions.x-serialize}}{{/readParams}}{{^isApiV1}}'PageToken' => page_token, 'Page' => page_number, + {{/isApiV1}} 'PageSize' => page_size, }) headers = Twilio::Values.of({}) diff --git a/src/main/resources/twilio-ruby/methodsMetadata.mustache b/src/main/resources/twilio-ruby/methodsMetadata.mustache new file mode 100644 index 000000000..ff049c295 --- /dev/null +++ b/src/main/resources/twilio-ruby/methodsMetadata.mustache @@ -0,0 +1,25 @@ + ## + # {{vendorExtensions.x-name}} the {{apiName}}InstanceMetadata + {{#queryParams}} + # @param [{{dataType}}] {{paramName}} {{{description}}} + {{/queryParams}} + {{#formParams}} + # @param [{{dataType}}] {{paramName}} {{{description}}} + {{/formParams}} + {{#headerParams}} + # @param [{{dataType}}] {{paramName}} {{{description}}} + {{/headerParams}} + {{#bodyParams}} + # @param [{{dataType}}] {{paramName}} {{{description}}} + {{/bodyParams}} + {{^vendorExtensions.x-is-delete-operation}} + # @return [{{apiName}}Instance] {{#vendorExtensions.x-is-fetch-operation}}{{vendorExtensions.x-name}}ed{{/vendorExtensions.x-is-fetch-operation}}{{^vendorExtensions.x-is-fetch-operation}}{{vendorExtensions.x-name}}d{{/vendorExtensions.x-is-fetch-operation}} {{apiName}}Instance + {{/vendorExtensions.x-is-delete-operation}} + {{#vendorExtensions.x-is-delete-operation}} + # @return [Boolean] True if delete succeeds, false otherwise + {{/vendorExtensions.x-is-delete-operation}} + def {{#lambda.camelcase}}{{vendorExtensions.x-name}}{{/lambda.camelcase}}_with_metadata{{#hasParams}}({{#queryParams}} + {{paramName}}: {{#required}}nil{{/required}}{{^required}}:unset{{/required}}{{^-last}}, {{/-last}}{{/queryParams}}{{#formParams.0}}{{#queryParams.0}}, {{/queryParams.0}}{{/formParams.0}}{{#formParams}} + {{paramName}}: {{#required}}nil{{/required}}{{^required}}:unset{{/required}}{{^-last}}, {{/-last}}{{/formParams}}{{#headerParams.0}}{{#queryParams.0}}, {{/queryParams.0}}{{^queryParams.0}}{{#formParams.0}}, {{/formParams.0}}{{/queryParams.0}}{{/headerParams.0}}{{#headerParams}} + {{paramName}}: {{#required}}nil{{/required}}{{^required}}:unset{{/required}}{{^-last}}, {{/-last}}{{/headerParams}}{{#bodyParams}}{{#headerParams.0}},{{/headerParams.0}}{{paramName}}: {{#required}}nil{{/required}}{{^required}}:unset{{/required}}{{^-last}}, {{/-last}}{{/bodyParams}} + ){{/hasParams}} diff --git a/src/main/resources/twilio-ruby/page.mustache b/src/main/resources/twilio-ruby/page.mustache index 23d5265f7..eabb019eb 100644 --- a/src/main/resources/twilio-ruby/page.mustache +++ b/src/main/resources/twilio-ruby/page.mustache @@ -1,4 +1,4 @@ - class {{apiName}}Page < Page + class {{apiName}}Page < {{#isApiV1}}Token{{/isApiV1}}Page ## # Initialize the {{apiName}}Page # @param [Version] version Version that contains the resource @@ -6,7 +6,9 @@ # @param [Hash] solution Path solution for the resource # @return [{{apiName}}Page] {{apiName}}Page def initialize(version, response, solution) - super(version, response) + {{^isApiV1}}super(version, response){{/isApiV1}} + {{#isApiV1}}apiV1Version = ApiV1Version.new version.domain, version + super(apiV1Version, response){{/isApiV1}} # Path Solution @solution = solution @@ -25,4 +27,4 @@ def to_s '' end - end \ No newline at end of file + end diff --git a/src/main/resources/twilio-ruby/pageMetadata.mustache b/src/main/resources/twilio-ruby/pageMetadata.mustache new file mode 100644 index 000000000..e7b78b691 --- /dev/null +++ b/src/main/resources/twilio-ruby/pageMetadata.mustache @@ -0,0 +1,54 @@ + class {{apiName}}PageMetadata < PageMetadata + attr_reader :{{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}}_page + + def initialize(version, response, solution, limit) + super(version, response) + @{{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}}_page = [] + @limit = limit + key = get_key(response.body) + number_of_records = response.body[key].size + while( limit != :unset && number_of_records <= limit ) + @{{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}}_page << {{apiName}}ListResponse.new(version, @payload, key) + @payload = self.next_page + break unless @payload + number_of_records += @payload.body[key].size + end + # Path Solution + @solution = solution + end + + def each + @{{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}}_page.each do |record| + yield record + end + end + + def to_s + ''; + end + end + class {{apiName}}ListResponse < InstanceListResource + + # @param [Array<{{apiName}}Instance>] instance + # @param [Hash{String => Object}] headers + # @param [Integer] status_code + def initialize(version, payload, key) + @{{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}} = payload.body[key].map do |data| + {{apiName}}Instance.new(version, data) + end + @headers = payload.headers + @status_code = payload.status_code + end + + def {{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}} + @{{#lambda.snakecase}}{{apiName}}{{/lambda.snakecase}} + end + + def headers + @headers + end + + def status_code + @status_code + end + end diff --git a/src/main/resources/twilio-ruby/parentContext.mustache b/src/main/resources/twilio-ruby/parentContext.mustache index a308cacb3..05660e2aa 100644 --- a/src/main/resources/twilio-ruby/parentContext.mustache +++ b/src/main/resources/twilio-ruby/parentContext.mustache @@ -7,6 +7,7 @@ {{>context}} {{/metaProperties.hasInstanceOperation}} {{>page}} +{{>pageMetadata}} {{>instance}} {{#parentDir}} end