From 2514074bfe2bf0406959e342d348b7280a032ece Mon Sep 17 00:00:00 2001 From: codat-sdk-codegen Date: Fri, 7 Aug 2026 11:55:26 +0000 Subject: [PATCH] platform: regenerate with the in-house pipeline @ b5f2513, version 5.0.1 -> 5.0.2 --- platform/RELEASES.md | 12 +- platform/USAGE.md | 98 +- platform/docs/models/errors/errormessage.md | 28 +- .../models/operations/addproductrequest.md | 16 +- .../configurecustomdatatyperequest.md | 20 +- .../configuresupplementaldatarequest.md | 20 +- .../models/operations/createapikeyrequest.md | 7 + .../models/operations/createcompanyrequest.md | 8 + .../operations/createconnectionrequest.md | 16 +- .../operations/createconnectionrequestbody.md | 16 +- .../createwebhookconsumerrequest.md | 8 + platform/docs/models/operations/datatype.md | 72 +- .../models/operations/deleteapikeyrequest.md | 14 +- .../models/operations/deletecompanyrequest.md | 14 +- .../operations/deleteconnectionrequest.md | 16 +- .../deletewebhookconsumerrequest.md | 14 +- .../getcompanyaccesstokenrequest.md | 14 +- .../operations/getcompanydatastatusrequest.md | 14 +- .../getcompanypushhistoryrequest.md | 22 +- .../models/operations/getcompanyrequest.md | 14 +- .../getcompanysyncsettingsrequest.md | 14 +- ...tconnectionmanagementaccesstokenrequest.md | 14 +- .../models/operations/getconnectionrequest.md | 16 +- ...eateupdatemodeloptionsbydatatyperequest.md | 18 +- .../getcustomdatatypeconfigurationrequest.md | 16 +- .../operations/getintegrationrequest.md | 14 +- .../getintegrationsbrandingrequest.md | 14 +- .../operations/getpulloperationrequest.md | 16 +- .../operations/getpushoperationrequest.md | 16 +- .../getreadvalidationresultsrequest.md | 16 +- ...getsupplementaldataconfigurationrequest.md | 18 +- .../models/operations/listcompaniesrequest.md | 22 +- .../operations/listconnectionsrequest.md | 22 +- .../listcustomdatatyperecordsrequest.md | 22 +- .../operations/listintegrationsrequest.md | 20 +- .../operations/listpulloperationsrequest.md | 22 +- .../models/operations/pathparamdatatype.md | 72 +- .../operations/refreshcompanydatarequest.md | 14 +- .../refreshcustomdatatyperequest.md | 18 +- .../operations/refreshdatatyperequest.md | 18 +- .../operations/refreshproductdatarequest.md | 18 +- .../refreshproductdatarequestbody.md | 17 +- .../models/operations/removeproductrequest.md | 16 +- .../operations/replacecompanyrequest.md | 18 +- .../setcompanysyncsettingsrequest.md | 16 +- .../setcompanysyncsettingsrequestbody.md | 21 +- ...connectionmanagementcorssettingsrequest.md | 8 + .../operations/setcorssettingsrequest.md | 8 + .../operations/unlinkconnectionrequest.md | 20 +- .../models/operations/updatecompanyrequest.md | 18 +- .../updateconnectionauthorizationrequest.md | 18 +- .../models/operations/updateprofilerequest.md | 8 + .../updateprofilesyncsettingsrequest.md | 8 + .../updateprofilesyncsettingsrequestbody.md | 20 +- platform/docs/models/shared/accesstoken.md | 10 + platform/docs/models/shared/apikeydetails.md | 24 +- platform/docs/models/shared/apikeys.md | 14 +- platform/docs/models/shared/branding.md | 18 +- platform/docs/models/shared/brandingbutton.md | 18 +- platform/docs/models/shared/brandingimage.md | 14 +- platform/docs/models/shared/brandinglogo.md | 18 +- .../models/shared/clientratelimitwebhook.md | 20 +- .../shared/clientratelimitwebhookpayload.md | 18 +- platform/docs/models/shared/companies.md | 22 +- platform/docs/models/shared/company.md | 48 +- .../docs/models/shared/companyaccesstoken.md | 22 +- platform/docs/models/shared/companydetails.md | 34 +- .../models/shared/companyproductwebhook.md | 11 + .../shared/companyproductwebhookpayload.md | 13 + .../docs/models/shared/companyreference.md | 22 +- .../models/shared/companyreferencelinks.md | 18 +- .../docs/models/shared/companyrequestbody.md | 18 +- .../docs/models/shared/companysyncsettings.md | 18 +- .../models/shared/companyupdaterequest.md | 18 +- platform/docs/models/shared/companywebhook.md | 20 +- platform/docs/models/shared/connection.md | 59 +- .../shared/connectionmanagementaccesstoken.md | 14 +- .../connectionmanagementallowedorigins.md | 16 +- platform/docs/models/shared/connections.md | 22 +- .../docs/models/shared/connectionwebhook.md | 20 +- .../models/shared/connectionwebhookpayload.md | 16 +- platform/docs/models/shared/content.md | 12 +- platform/docs/models/shared/createapikey.md | 18 +- .../models/shared/createconnectionrequest.md | 8 + platform/docs/models/shared/currentstatus.md | 36 + .../shared/customdatatypeconfiguration.md | 24 +- .../models/shared/customdatatyperecord.md | 18 +- .../models/shared/customdatatyperecords.md | 24 +- .../docs/models/shared/dataconnectionerror.md | 24 +- .../models/shared/dataconnectionstatus.md | 40 +- platform/docs/models/shared/datasetstatus.md | 74 +- platform/docs/models/shared/datastatus.md | 26 +- platform/docs/models/shared/datastatuses.md | 98 +- platform/docs/models/shared/datatype.md | 135 +- .../docs/models/shared/datatypefeature.md | 20 +- .../docs/models/shared/datatypereadsummary.md | 24 +- platform/docs/models/shared/datatypes.md | 118 +- .../models/shared/datatypewritewebhook.md | 20 +- .../shared/datatypewritewebhookpayload.md | 32 +- .../shared/datatypewritewebhookrecord.md | 14 +- platform/docs/models/shared/errormessage.md | 28 +- platform/docs/models/shared/errorstatus.md | 36 +- .../docs/models/shared/errorvalidation.md | 18 +- .../docs/models/shared/errorvalidationitem.md | 18 +- platform/docs/models/shared/featurestate.md | 44 +- platform/docs/models/shared/featuretype.md | 50 +- platform/docs/models/shared/halref.md | 14 +- platform/docs/models/shared/imagereference.md | 20 +- platform/docs/models/shared/integration.md | 38 +- platform/docs/models/shared/integrations.md | 22 +- platform/docs/models/shared/issue.md | 22 +- platform/docs/models/shared/issuelinks.md | 18 +- platform/docs/models/shared/links.md | 20 +- platform/docs/models/shared/modifieddate.md | 14 +- platform/docs/models/shared/paginginfo.md | 11 + platform/docs/models/shared/profile.md | 30 +- platform/docs/models/shared/pulloperation.md | 42 +- platform/docs/models/shared/pulloperations.md | 22 +- platform/docs/models/shared/pushchangetype.md | 42 +- .../docs/models/shared/pushfieldvalidation.md | 19 +- platform/docs/models/shared/pushoperation.md | 38 +- .../docs/models/shared/pushoperationchange.md | 20 +- .../docs/models/shared/pushoperationref.md | 19 +- platform/docs/models/shared/pushoperations.md | 22 +- .../docs/models/shared/pushoperationstatus.md | 40 +- platform/docs/models/shared/pushoption.md | 26 +- .../docs/models/shared/pushoptionchoice.md | 22 +- .../docs/models/shared/pushoptionproperty.md | 26 +- platform/docs/models/shared/pushoptiontype.md | 46 +- .../docs/models/shared/pushvalidationinfo.md | 17 +- .../models/shared/readcompletedwebhook.md | 20 +- .../shared/readcompletedwebhookpayload.md | 20 +- .../shared/refreshproductdatarequest.md | 9 + platform/docs/models/shared/schemadatatype.md | 118 +- platform/docs/models/shared/security.md | 16 +- .../shared/setcompanysyncsettingsrequest.md | 10 + platform/docs/models/shared/sourcetype.md | 46 +- platform/docs/models/shared/status.md | 72 +- .../shared/supplementaldataconfiguration.md | 14 +- .../supplementaldatasourceconfiguration.md | 22 +- .../docs/models/shared/supportedfeature.md | 18 +- platform/docs/models/shared/syncsetting.md | 32 +- platform/docs/models/shared/syncsettings.md | 18 +- .../models/shared/updateconnectionstatus.md | 15 +- .../updateprofilesyncsettingsrequest.md | 10 + platform/docs/models/shared/validation.md | 20 +- platform/docs/models/shared/validationitem.md | 19 +- .../docs/models/shared/validationitem1.md | 20 +- .../docs/models/shared/validationresult.md | 16 +- .../docs/models/shared/webhookconsumer.md | 32 +- .../models/shared/webhookconsumerprototype.md | 20 +- .../docs/models/shared/webhookconsumers.md | 14 +- .../docs/models/shared/webhookzapierkey.md | 8 + platform/docs/models/shared/writestatus.md | 38 +- platform/docs/models/shared/writetype.md | 40 +- platform/docs/models/utils/retryconfig.md | 46 +- platform/docs/sdks/companies/README.md | 1715 ++++++----- .../docs/sdks/connectionmanagement/README.md | 124 +- platform/docs/sdks/connections/README.md | 642 ++-- platform/docs/sdks/cors/README.md | 274 +- platform/docs/sdks/customdatatype/README.md | 732 +++-- platform/docs/sdks/integrations/README.md | 298 +- platform/docs/sdks/pushdata/README.md | 321 +- platform/docs/sdks/readdata/README.md | 119 +- platform/docs/sdks/refreshdata/README.md | 493 ++- platform/docs/sdks/settings/README.md | 1090 ++++--- platform/docs/sdks/supplementaldata/README.md | 546 ++-- platform/docs/sdks/webhooks/README.md | 412 +-- platform/pyproject.toml | 55 +- platform/src/codat_platform/__init__.py | 158 +- .../src/codat_platform/_hooks/__init__.py | 31 +- .../src/codat_platform/_hooks/sdkhooks.py | 111 +- platform/src/codat_platform/_hooks/types.py | 68 +- .../src/codat_platform/_httpx_transport.py | 130 + platform/src/codat_platform/_version.py | 13 +- platform/src/codat_platform/api/__init__.py | 16 + platform/src/codat_platform/api/companies.py | 2704 +++++++++++++++++ .../api/connection_management.py | 259 ++ .../src/codat_platform/api/connections.py | 1416 +++++++++ platform/src/codat_platform/api/cors.py | 455 +++ .../codat_platform/api/custom_data_type.py | 961 ++++++ .../src/codat_platform/api/integrations.py | 704 +++++ platform/src/codat_platform/api/push_data.py | 732 +++++ platform/src/codat_platform/api/read_data.py | 264 ++ .../src/codat_platform/api/refresh_data.py | 1154 +++++++ platform/src/codat_platform/api/settings.py | 1897 ++++++++++++ .../codat_platform/api/supplemental_data.py | 498 +++ platform/src/codat_platform/api/webhooks.py | 850 ++++++ platform/src/codat_platform/api_client.py | 803 +++++ platform/src/codat_platform/api_response.py | 21 + platform/src/codat_platform/basesdk.py | 393 --- platform/src/codat_platform/companies.py | 2512 +-------------- platform/src/codat_platform/configuration.py | 596 ++++ .../codat_platform/connection_management.py | 227 +- platform/src/codat_platform/connections.py | 1240 +------- platform/src/codat_platform/cors.py | 435 +-- .../src/codat_platform/custom_data_type.py | 856 +----- platform/src/codat_platform/exceptions.py | 200 ++ platform/src/codat_platform/integrations.py | 604 +--- .../src/codat_platform/models/__init__.py | 124 +- .../codat_platform/models/_compat/__init__.py | 3 + .../models/_compat/schema_datatype.py | 50 + .../src/codat_platform/models/access_token.py | 105 + .../models/company_product_webhook.py | 112 + .../models/company_product_webhook_payload.py | 114 + .../models/company_reference_links.py | 99 + platform/src/codat_platform/models/content.py | 27 + .../models/create_connection_request.py | 110 + .../codat_platform/models/current_status.py | 28 + .../src/codat_platform/models/data_types.py | 50 + .../codat_platform/models/dataset_status.py | 28 + .../src/codat_platform/models/error_status.py | 9 + .../codat_platform/models/errors/__init__.py | 35 +- .../models/errors/codatplatformerror.py | 74 +- .../models/errors/errormessage.py | 74 +- .../models/errors/no_response_error.py | 11 +- .../models/errors/responsevalidationerror.py | 45 +- .../codat_platform/models/errors/sdkerror.py | 55 +- .../src/codat_platform/models/issue_links.py | 105 + .../codat_platform/models/modified_date.py | 99 + .../models/operations/__init__.py | 455 +-- .../models/operations/add_product.py | 32 +- .../operations/configure_custom_data_type.py | 63 +- .../operations/configure_supplemental_data.py | 106 +- .../models/operations/create_connection.py | 81 +- .../models/operations/delete_api_key.py | 23 +- .../models/operations/delete_company.py | 23 +- .../models/operations/delete_connection.py | 32 +- .../operations/delete_webhook_consumer.py | 23 +- .../models/operations/get_company.py | 23 +- .../operations/get_company_access_token.py | 23 +- .../operations/get_company_data_status.py | 23 +- .../operations/get_company_push_history.py | 75 +- .../operations/get_company_syncsettings.py | 23 +- .../models/operations/get_connection.py | 32 +- .../get_connection_management_access_token.py | 23 +- ...reate_update_model_options_by_data_type.py | 42 +- .../get_custom_data_type_configuration.py | 32 +- .../models/operations/get_integration.py | 23 +- .../operations/get_integrations_branding.py | 23 +- .../models/operations/get_pull_operation.py | 32 +- .../models/operations/get_push_operation.py | 32 +- .../operations/get_read_validation_results.py | 32 +- .../get_supplemental_data_configuration.py | 75 +- .../models/operations/list_companies.py | 74 +- .../models/operations/list_connections.py | 75 +- .../list_custom_data_type_records.py | 76 +- .../models/operations/list_integrations.py | 66 +- .../models/operations/list_pull_operations.py | 75 +- .../models/operations/refresh_company_data.py | 23 +- .../operations/refresh_custom_data_type.py | 41 +- .../models/operations/refresh_data_type.py | 60 +- .../models/operations/refresh_product_data.py | 96 +- .../models/operations/remove_product.py | 32 +- .../models/operations/replace_company.py | 50 +- .../operations/set_company_syncsettings.py | 106 +- .../models/operations/unlink_connection.py | 61 +- .../models/operations/update_company.py | 52 +- .../update_connection_authorization.py | 56 +- .../operations/update_profile_syncsettings.py | 61 +- .../src/codat_platform/models/paging_info.py | 113 + .../models/refresh_product_data_request.py | 113 + .../set_company_sync_settings_request.py | 113 + .../codat_platform/models/shared/__init__.py | 895 +++--- .../models/shared/apikeydetails.py | 183 +- .../codat_platform/models/shared/apikeys.py | 121 +- .../codat_platform/models/shared/branding.py | 135 +- .../models/shared/brandingbutton.py | 120 +- .../models/shared/brandingimage.py | 113 +- .../models/shared/brandinglogo.py | 120 +- .../models/shared/clientratelimitwebhook.py | 155 +- .../shared/clientratelimitwebhookpayload.py | 143 +- .../codat_platform/models/shared/companies.py | 148 +- .../codat_platform/models/shared/company.py | 344 +-- .../models/shared/companyaccesstoken.py | 117 +- .../models/shared/companydetails.py | 312 +- .../models/shared/companyreference.py | 149 +- .../models/shared/companyrequestbody.py | 130 +- .../models/shared/companysyncsettings.py | 134 +- .../models/shared/companyupdaterequest.py | 133 +- .../models/shared/companywebhook.py | 152 +- .../models/shared/connection.py | 349 +-- .../shared/connectionmanagementaccesstoken.py | 111 +- .../connectionmanagementallowedorigins.py | 115 +- .../models/shared/connections.py | 148 +- .../models/shared/connectionwebhook.py | 155 +- .../models/shared/connectionwebhookpayload.py | 137 +- .../models/shared/createapikey.py | 141 +- .../shared/customdatatypeconfiguration.py | 169 +- .../models/shared/customdatatyperecord.py | 162 +- .../models/shared/customdatatyperecords.py | 143 +- .../models/shared/dataconnectionerror.py | 253 +- .../models/shared/dataconnectionstatus.py | 39 +- .../models/shared/datastatus.py | 240 +- .../models/shared/datastatuses.py | 670 ++-- .../codat_platform/models/shared/datatype.py | 134 +- .../models/shared/datatypefeature.py | 140 +- .../models/shared/datatypereadsummary.py | 204 +- .../models/shared/datatypewritewebhook.py | 155 +- .../shared/datatypewritewebhookpayload.py | 296 +- .../shared/datatypewritewebhookrecord.py | 108 +- .../models/shared/errormessage.py | 200 +- .../models/shared/errorvalidation.py | 154 +- .../models/shared/errorvalidationitem.py | 156 +- .../models/shared/featurestate.py | 44 +- .../models/shared/featuretype.py | 52 +- .../codat_platform/models/shared/halref.py | 108 +- .../models/shared/imagereference.py | 116 +- .../models/shared/integration.py | 214 +- .../models/shared/integrations.py | 148 +- .../src/codat_platform/models/shared/issue.py | 143 +- .../src/codat_platform/models/shared/links.py | 137 +- .../codat_platform/models/shared/profile.py | 179 +- .../models/shared/pulloperation.py | 338 +-- .../models/shared/pulloperations.py | 148 +- .../models/shared/pushchangetype.py | 40 +- .../models/shared/pushfieldvalidation.py | 163 +- .../models/shared/pushoperation.py | 353 +-- .../models/shared/pushoperationchange.py | 164 +- .../models/shared/pushoperationref.py | 145 +- .../models/shared/pushoperations.py | 148 +- .../models/shared/pushoperationstatus.py | 38 +- .../models/shared/pushoption.py | 202 +- .../models/shared/pushoptionchoice.py | 140 +- .../models/shared/pushoptionproperty.py | 200 +- .../models/shared/pushoptiontype.py | 48 +- .../models/shared/pushvalidationinfo.py | 168 +- .../models/shared/readcompletedwebhook.py | 155 +- .../shared/readcompletedwebhookpayload.py | 175 +- .../models/shared/schema_datatype.py | 50 +- .../codat_platform/models/shared/security.py | 24 +- .../models/shared/sourcetype.py | 47 +- .../codat_platform/models/shared/status.py | 74 +- .../shared/supplementaldataconfiguration.py | 155 +- .../models/shared/supportedfeature.py | 115 +- .../models/shared/syncsetting.py | 202 +- .../models/shared/syncsettings.py | 134 +- .../models/shared/updateconnectionstatus.py | 124 +- .../models/shared/validation.py | 154 +- .../models/shared/validationitem.py | 170 +- .../models/shared/validationitem1.py | 57 - .../models/shared/validationresult.py | 129 +- .../models/shared/webhookconsumer.py | 172 +- .../models/shared/webhookconsumerprototype.py | 166 +- .../models/shared/webhookconsumers.py | 116 +- .../models/shared/writestatus.py | 38 +- .../codat_platform/models/shared/writetype.py | 38 +- .../supplemental_data_source_configuration.py | 105 + .../update_profile_sync_settings_request.py | 121 + .../codat_platform/models/validation_item1.py | 108 + .../codat_platform/models/validationitem1.py | 33 + .../models/webhook_zapier_key.py | 99 + platform/src/codat_platform/push_data.py | 622 +--- platform/src/codat_platform/py.typed | 1 - platform/src/codat_platform/read_data.py | 224 +- platform/src/codat_platform/refresh_data.py | 1006 +----- platform/src/codat_platform/rest.py | 258 ++ platform/src/codat_platform/sdk.py | 371 +-- .../src/codat_platform/sdkconfiguration.py | 49 - platform/src/codat_platform/settings.py | 1810 +---------- .../src/codat_platform/supplemental_data.py | 450 +-- platform/src/codat_platform/types/__init__.py | 73 +- .../src/codat_platform/types/basemodel.py | 77 - platform/src/codat_platform/utils/__init__.py | 176 +- .../src/codat_platform/utils/annotations.py | 79 - .../src/codat_platform/utils/datetimes.py | 23 - .../codat_platform/utils/dynamic_imports.py | 54 - platform/src/codat_platform/utils/enums.py | 134 - .../codat_platform/utils/eventstreaming.py | 309 -- platform/src/codat_platform/utils/forms.py | 234 -- platform/src/codat_platform/utils/headers.py | 136 - platform/src/codat_platform/utils/logger.py | 22 - platform/src/codat_platform/utils/metadata.py | 119 - .../src/codat_platform/utils/queryparams.py | 217 -- .../src/codat_platform/utils/requestbodies.py | 66 - platform/src/codat_platform/utils/retries.py | 343 +-- platform/src/codat_platform/utils/security.py | 198 -- .../src/codat_platform/utils/serializers.py | 225 -- .../utils/unmarshal_json_response.py | 38 - platform/src/codat_platform/utils/url.py | 155 - platform/src/codat_platform/utils/values.py | 137 - platform/src/codat_platform/webhooks.py | 614 +--- .../src/codatplatform/_hooks/registration.py | 13 - 383 files changed, 30555 insertions(+), 26944 deletions(-) create mode 100644 platform/docs/models/operations/createapikeyrequest.md create mode 100644 platform/docs/models/operations/createcompanyrequest.md create mode 100644 platform/docs/models/operations/createwebhookconsumerrequest.md create mode 100644 platform/docs/models/operations/setconnectionmanagementcorssettingsrequest.md create mode 100644 platform/docs/models/operations/setcorssettingsrequest.md create mode 100644 platform/docs/models/operations/updateprofilerequest.md create mode 100644 platform/docs/models/operations/updateprofilesyncsettingsrequest.md create mode 100644 platform/docs/models/shared/accesstoken.md create mode 100644 platform/docs/models/shared/companyproductwebhook.md create mode 100644 platform/docs/models/shared/companyproductwebhookpayload.md create mode 100644 platform/docs/models/shared/createconnectionrequest.md create mode 100644 platform/docs/models/shared/currentstatus.md create mode 100644 platform/docs/models/shared/paginginfo.md create mode 100644 platform/docs/models/shared/refreshproductdatarequest.md create mode 100644 platform/docs/models/shared/setcompanysyncsettingsrequest.md create mode 100644 platform/docs/models/shared/updateprofilesyncsettingsrequest.md create mode 100644 platform/docs/models/shared/webhookzapierkey.md create mode 100644 platform/src/codat_platform/_httpx_transport.py create mode 100644 platform/src/codat_platform/api/__init__.py create mode 100644 platform/src/codat_platform/api/companies.py create mode 100644 platform/src/codat_platform/api/connection_management.py create mode 100644 platform/src/codat_platform/api/connections.py create mode 100644 platform/src/codat_platform/api/cors.py create mode 100644 platform/src/codat_platform/api/custom_data_type.py create mode 100644 platform/src/codat_platform/api/integrations.py create mode 100644 platform/src/codat_platform/api/push_data.py create mode 100644 platform/src/codat_platform/api/read_data.py create mode 100644 platform/src/codat_platform/api/refresh_data.py create mode 100644 platform/src/codat_platform/api/settings.py create mode 100644 platform/src/codat_platform/api/supplemental_data.py create mode 100644 platform/src/codat_platform/api/webhooks.py create mode 100644 platform/src/codat_platform/api_client.py create mode 100644 platform/src/codat_platform/api_response.py delete mode 100644 platform/src/codat_platform/basesdk.py create mode 100644 platform/src/codat_platform/configuration.py create mode 100644 platform/src/codat_platform/exceptions.py create mode 100644 platform/src/codat_platform/models/_compat/__init__.py create mode 100644 platform/src/codat_platform/models/_compat/schema_datatype.py create mode 100644 platform/src/codat_platform/models/access_token.py create mode 100644 platform/src/codat_platform/models/company_product_webhook.py create mode 100644 platform/src/codat_platform/models/company_product_webhook_payload.py create mode 100644 platform/src/codat_platform/models/company_reference_links.py create mode 100644 platform/src/codat_platform/models/content.py create mode 100644 platform/src/codat_platform/models/create_connection_request.py create mode 100644 platform/src/codat_platform/models/current_status.py create mode 100644 platform/src/codat_platform/models/data_types.py create mode 100644 platform/src/codat_platform/models/dataset_status.py create mode 100644 platform/src/codat_platform/models/error_status.py create mode 100644 platform/src/codat_platform/models/issue_links.py create mode 100644 platform/src/codat_platform/models/modified_date.py create mode 100644 platform/src/codat_platform/models/paging_info.py create mode 100644 platform/src/codat_platform/models/refresh_product_data_request.py create mode 100644 platform/src/codat_platform/models/set_company_sync_settings_request.py delete mode 100644 platform/src/codat_platform/models/shared/validationitem1.py create mode 100644 platform/src/codat_platform/models/supplemental_data_source_configuration.py create mode 100644 platform/src/codat_platform/models/update_profile_sync_settings_request.py create mode 100644 platform/src/codat_platform/models/validation_item1.py create mode 100644 platform/src/codat_platform/models/validationitem1.py create mode 100644 platform/src/codat_platform/models/webhook_zapier_key.py create mode 100644 platform/src/codat_platform/rest.py delete mode 100644 platform/src/codat_platform/sdkconfiguration.py delete mode 100644 platform/src/codat_platform/types/basemodel.py delete mode 100644 platform/src/codat_platform/utils/annotations.py delete mode 100644 platform/src/codat_platform/utils/datetimes.py delete mode 100644 platform/src/codat_platform/utils/dynamic_imports.py delete mode 100644 platform/src/codat_platform/utils/enums.py delete mode 100644 platform/src/codat_platform/utils/eventstreaming.py delete mode 100644 platform/src/codat_platform/utils/forms.py delete mode 100644 platform/src/codat_platform/utils/headers.py delete mode 100644 platform/src/codat_platform/utils/logger.py delete mode 100644 platform/src/codat_platform/utils/metadata.py delete mode 100644 platform/src/codat_platform/utils/queryparams.py delete mode 100644 platform/src/codat_platform/utils/requestbodies.py delete mode 100644 platform/src/codat_platform/utils/security.py delete mode 100644 platform/src/codat_platform/utils/serializers.py delete mode 100644 platform/src/codat_platform/utils/unmarshal_json_response.py delete mode 100644 platform/src/codat_platform/utils/url.py delete mode 100644 platform/src/codat_platform/utils/values.py delete mode 100644 platform/src/codatplatform/_hooks/registration.py diff --git a/platform/RELEASES.md b/platform/RELEASES.md index a93376b17..293e21cdd 100644 --- a/platform/RELEASES.md +++ b/platform/RELEASES.md @@ -158,4 +158,14 @@ Based on: ### Generated - [python v5.0.1] platform ### Releases -- [PyPI v5.0.1] https://pypi.org/project/codat-platform/5.0.1 - platform \ No newline at end of file +- [PyPI v5.0.1] https://pypi.org/project/codat-platform/5.0.1 - platform + +## 2026-08-07 11:55:25 +### Changes +Based on: +- OpenAPI Doc 3.0.0 https://raw.githubusercontent.com/codatio/oas/main/yaml/Codat-Platform.yaml +- codat sdk-codegen b5f25135143b1ccfb99c941df11a7a1596dbe31e https://github.com/codat-spikes/sdk-codegen +### Generated +- [python v5.0.2] platform +### Releases +- [PyPI v5.0.2] https://pypi.org/project/codat-platform/5.0.2 - platform diff --git a/platform/USAGE.md b/platform/USAGE.md index 20cc759de..dbbfb0014 100644 --- a/platform/USAGE.md +++ b/platform/USAGE.md @@ -1,49 +1,51 @@ - -```python -# Synchronous Example -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.settings.create_api_key(request={ - "name": "azure-invoice-finance-processor", - }) - - # Handle response - print(res) -``` - -
- -The same SDK client can also be used to make asynchronous requests by importing asyncio. - -```python -# Asynchronous Example -import asyncio -from codat_platform import CodatPlatform -from codat_platform.models import shared - -async def main(): - - async with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), - ) as cp_client: - - res = await cp_client.settings.create_api_key_async(request={ - "name": "azure-invoice-finance-processor", - }) - - # Handle response - print(res) - -asyncio.run(main()) -``` + +```python +# Synchronous Example +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.add_product(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "product_identifier": "bank-feeds", + }) + + # Handle response + print(res) +``` + +
+ +The same SDK client can also be used to make asynchronous requests by importing asyncio. + +```python +# Asynchronous Example +import asyncio +from codat_platform import CodatPlatform +from codat_platform.models import shared + +async def main(): + + async with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), + ) as cp_client: + + res = await cp_client.companies.add_product_async(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "product_identifier": "bank-feeds", + }) + + # Handle response + print(res) + +asyncio.run(main()) +``` \ No newline at end of file diff --git a/platform/docs/models/errors/errormessage.md b/platform/docs/models/errors/errormessage.md index c795816c6..eeefa0c01 100644 --- a/platform/docs/models/errors/errormessage.md +++ b/platform/docs/models/errors/errormessage.md @@ -1,16 +1,14 @@ -# ErrorMessage - -Your API request was not properly authorized. - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `can_be_retried` | *Optional[str]* | :heavy_minus_sign: | `True` if the error occurred transiently and can be retried. | -| `correlation_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier used to propagate to all downstream services and determine the source of the error. | -| `detailed_error_code` | *Optional[int]* | :heavy_minus_sign: | Machine readable error code used to automate processes based on the code returned. | -| `error` | *Optional[str]* | :heavy_minus_sign: | A brief description of the error. | -| `service` | *Optional[str]* | :heavy_minus_sign: | Codat's service the returned the error. | -| `status_code` | *Optional[int]* | :heavy_minus_sign: | The HTTP status code returned by the error. | +# ErrorMessage + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `can_be_retried` | *Optional[str]* | :heavy_minus_sign: | `True` if the error occurred transiently and can be retried. | +| `correlation_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier used to propagate to all downstream services and determine the source of the error. | +| `detailed_error_code` | *Optional[int]* | :heavy_minus_sign: | Machine readable error code used to automate processes based on the code returned. | +| `error` | *Optional[str]* | :heavy_minus_sign: | A brief description of the error. | +| `service` | *Optional[str]* | :heavy_minus_sign: | Codat's service the returned the error. | +| `status_code` | *Optional[int]* | :heavy_minus_sign: | The HTTP status code returned by the error. | | `validation` | [OptionalNullable[shared.ErrorValidation]](../../models/shared/errorvalidation.md) | :heavy_minus_sign: | A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here. | \ No newline at end of file diff --git a/platform/docs/models/operations/addproductrequest.md b/platform/docs/models/operations/addproductrequest.md index 502eee809..0b18159be 100644 --- a/platform/docs/models/operations/addproductrequest.md +++ b/platform/docs/models/operations/addproductrequest.md @@ -1,9 +1,9 @@ -# AddProductRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# AddProductRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `product_identifier` | *str* | :heavy_check_mark: | Human-readable product identifier for a product. | **Example 1:** bank-feeds
**Example 2:** lending
**Example 3:** payables
**Example 4:** expenses | \ No newline at end of file diff --git a/platform/docs/models/operations/configurecustomdatatyperequest.md b/platform/docs/models/operations/configurecustomdatatyperequest.md index 6f2df75e6..7598fc04e 100644 --- a/platform/docs/models/operations/configurecustomdatatyperequest.md +++ b/platform/docs/models/operations/configurecustomdatatyperequest.md @@ -1,10 +1,10 @@ -# ConfigureCustomDataTypeRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `custom_data_type_configuration` | [Optional[shared.CustomDataTypeConfiguration]](../../models/shared/customdatatypeconfiguration.md) | :heavy_minus_sign: | Custom data type configuration for the specified platform. | {
"dataSource": "api/purchaseOrders?$filter=currencyCode eq 'NOK'",
"requiredData": {
"currencyCode": "$[*].currencyCode",
"id": "$[*].id",
"number": "$[*].number",
"orderDate": "$[*].orderDate",
"totalAmountExcludingTax": "$[*].totalAmountExcludingTax",
"totalTaxAmount": "$[*].totalTaxAmount",
"vendorName": "$[*].number"
},
"keyBy": [
"$[*].id"
],
"sourceModifiedDate": [
"$[*].lastModifiedDateTime"
]
} | -| `custom_data_identifier` | *str* | :heavy_check_mark: | Unique identifier for a custom data type. | DynamicsPurchaseOrders | -| `platform_key` | *str* | :heavy_check_mark: | A unique 4-letter key to represent a platform in each integration. | gbol | \ No newline at end of file +# ConfigureCustomDataTypeRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `custom_data_identifier` | *str* | :heavy_check_mark: | Unique identifier for a custom data type. | DynamicsPurchaseOrders | +| `custom_data_type_configuration` | [Optional[shared.CustomDataTypeConfiguration]](../../models/shared/customdatatypeconfiguration.md) | :heavy_minus_sign: | Custom data type configuration for the specified platform. | | +| `platform_key` | *str* | :heavy_check_mark: | A unique 4-letter key to represent a platform in each integration. | gbol | \ No newline at end of file diff --git a/platform/docs/models/operations/configuresupplementaldatarequest.md b/platform/docs/models/operations/configuresupplementaldatarequest.md index 85fc38aca..b410f8b00 100644 --- a/platform/docs/models/operations/configuresupplementaldatarequest.md +++ b/platform/docs/models/operations/configuresupplementaldatarequest.md @@ -1,10 +1,10 @@ -# ConfigureSupplementalDataRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `supplemental_data_configuration` | [Optional[shared.SupplementalDataConfiguration]](../../models/shared/supplementaldataconfiguration.md) | :heavy_minus_sign: | The configuration for the specified platform and data type. | {
"supplementalDataConfig": {
"orders-supplemental-data": {
"dataSource": "/orders",
"pullData": {
"orderNumber": "order_num"
},
"pushData": {
"orderNumber": "order_num"
}
}
}
} | -| `data_type` | [operations.DataType](../../models/operations/datatype.md) | :heavy_check_mark: | Supported supplemental data data type. | invoices | -| `platform_key` | *str* | :heavy_check_mark: | A unique 4-letter key to represent a platform in each integration. | gbol | \ No newline at end of file +# ConfigureSupplementalDataRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `data_type` | *str* | :heavy_check_mark: | Supported supplemental data data type. | invoices | +| `platform_key` | *str* | :heavy_check_mark: | A unique 4-letter key to represent a platform in each integration. | gbol | +| `supplemental_data_configuration` | [Optional[shared.SupplementalDataConfiguration]](../../models/shared/supplementaldataconfiguration.md) | :heavy_minus_sign: | The configuration for the specified platform and data type. | | \ No newline at end of file diff --git a/platform/docs/models/operations/createapikeyrequest.md b/platform/docs/models/operations/createapikeyrequest.md new file mode 100644 index 000000000..e7fc85db0 --- /dev/null +++ b/platform/docs/models/operations/createapikeyrequest.md @@ -0,0 +1,7 @@ +# CreateAPIKeyRequest + + +## Fields + +| Field | Type | Required | Description | +| ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/platform/docs/models/operations/createcompanyrequest.md b/platform/docs/models/operations/createcompanyrequest.md new file mode 100644 index 000000000..ebd7ca0a0 --- /dev/null +++ b/platform/docs/models/operations/createcompanyrequest.md @@ -0,0 +1,8 @@ +# CreateCompanyRequest + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `company_request_body` | [Optional[shared.CompanyRequestBody]](../../models/shared/companyrequestbody.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/operations/createconnectionrequest.md b/platform/docs/models/operations/createconnectionrequest.md index 0998495bf..32316fd7b 100644 --- a/platform/docs/models/operations/createconnectionrequest.md +++ b/platform/docs/models/operations/createconnectionrequest.md @@ -1,9 +1,9 @@ -# CreateConnectionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `request_body` | [Optional[operations.CreateConnectionRequestBody]](../../models/operations/createconnectionrequestbody.md) | :heavy_minus_sign: | N/A | | +# CreateConnectionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `request_body` | [Optional[operations.CreateConnectionRequestBody]](../../models/operations/createconnectionrequestbody.md) | :heavy_minus_sign: | N/A | | | `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/platform/docs/models/operations/createconnectionrequestbody.md b/platform/docs/models/operations/createconnectionrequestbody.md index 891314d08..5a6200d18 100644 --- a/platform/docs/models/operations/createconnectionrequestbody.md +++ b/platform/docs/models/operations/createconnectionrequestbody.md @@ -1,8 +1,8 @@ -# CreateConnectionRequestBody - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `platform_key` | *Optional[str]* | :heavy_minus_sign: | A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys. | gbol | \ No newline at end of file +# CreateConnectionRequestBody + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `platform_key` | *Optional[str]* | :heavy_minus_sign: | A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys. | \ No newline at end of file diff --git a/platform/docs/models/operations/createwebhookconsumerrequest.md b/platform/docs/models/operations/createwebhookconsumerrequest.md new file mode 100644 index 000000000..0359b4c5c --- /dev/null +++ b/platform/docs/models/operations/createwebhookconsumerrequest.md @@ -0,0 +1,8 @@ +# CreateWebhookConsumerRequest + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| `webhook_consumer_prototype` | [Optional[shared.WebhookConsumerPrototype]](../../models/shared/webhookconsumerprototype.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/operations/datatype.md b/platform/docs/models/operations/datatype.md index 22092bdaf..ea3c4133c 100644 --- a/platform/docs/models/operations/datatype.md +++ b/platform/docs/models/operations/datatype.md @@ -1,38 +1,36 @@ -# DataType - -Data types that support supplemental data - -## Example Usage - -```python -from codat_platform.models.operations import DataType - -value = DataType.CHART_OF_ACCOUNTS -``` - - -## Values - -| Name | Value | -| ----------------------------- | ----------------------------- | -| `CHART_OF_ACCOUNTS` | chartOfAccounts | -| `BILLS` | bills | -| `COMPANY` | company | -| `CREDIT_NOTES` | creditNotes | -| `CUSTOMERS` | customers | -| `INVOICES` | invoices | -| `ITEMS` | items | -| `JOURNAL_ENTRIES` | journalEntries | -| `SUPPLIERS` | suppliers | -| `TAX_RATES` | taxRates | -| `COMMERCE_COMPANY_INFO` | commerce-companyInfo | -| `COMMERCE_CUSTOMERS` | commerce-customers | -| `COMMERCE_DISPUTES` | commerce-disputes | -| `COMMERCE_LOCATIONS` | commerce-locations | -| `COMMERCE_ORDERS` | commerce-orders | -| `COMMERCE_PAYMENTS` | commerce-payments | -| `COMMERCE_PAYMENT_METHODS` | commerce-paymentMethods | -| `COMMERCE_PRODUCTS` | commerce-products | -| `COMMERCE_PRODUCT_CATEGORIES` | commerce-productCategories | -| `COMMERCE_TAX_COMPONENTS` | commerce-taxComponents | +# DataType + +## Example Usage + +```python +from codat_platform.models.operations import DataType + +value = DataType.CHART_OF_ACCOUNTS +``` + + +## Values + +| Name | Value | +| ----------------------------- | ----------------------------- | +| `CHART_OF_ACCOUNTS` | chartOfAccounts | +| `BILLS` | bills | +| `COMPANY` | company | +| `CREDIT_NOTES` | creditNotes | +| `CUSTOMERS` | customers | +| `INVOICES` | invoices | +| `ITEMS` | items | +| `JOURNAL_ENTRIES` | journalEntries | +| `SUPPLIERS` | suppliers | +| `TAX_RATES` | taxRates | +| `COMMERCE_COMPANY_INFO` | commerce-companyInfo | +| `COMMERCE_CUSTOMERS` | commerce-customers | +| `COMMERCE_DISPUTES` | commerce-disputes | +| `COMMERCE_LOCATIONS` | commerce-locations | +| `COMMERCE_ORDERS` | commerce-orders | +| `COMMERCE_PAYMENTS` | commerce-payments | +| `COMMERCE_PAYMENT_METHODS` | commerce-paymentMethods | +| `COMMERCE_PRODUCTS` | commerce-products | +| `COMMERCE_PRODUCT_CATEGORIES` | commerce-productCategories | +| `COMMERCE_TAX_COMPONENTS` | commerce-taxComponents | | `COMMERCE_TRANSACTIONS` | commerce-transactions | \ No newline at end of file diff --git a/platform/docs/models/operations/deleteapikeyrequest.md b/platform/docs/models/operations/deleteapikeyrequest.md index 3f73cc096..7f283ef9f 100644 --- a/platform/docs/models/operations/deleteapikeyrequest.md +++ b/platform/docs/models/operations/deleteapikeyrequest.md @@ -1,8 +1,8 @@ -# DeleteAPIKeyRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# DeleteAPIKeyRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `api_key_id` | *str* | :heavy_check_mark: | Unique identifier for api key. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/platform/docs/models/operations/deletecompanyrequest.md b/platform/docs/models/operations/deletecompanyrequest.md index 338ee40e5..6f16204ca 100644 --- a/platform/docs/models/operations/deletecompanyrequest.md +++ b/platform/docs/models/operations/deletecompanyrequest.md @@ -1,8 +1,8 @@ -# DeleteCompanyRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# DeleteCompanyRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/platform/docs/models/operations/deleteconnectionrequest.md b/platform/docs/models/operations/deleteconnectionrequest.md index 9650dc387..f4b0d4cb4 100644 --- a/platform/docs/models/operations/deleteconnectionrequest.md +++ b/platform/docs/models/operations/deleteconnectionrequest.md @@ -1,9 +1,9 @@ -# DeleteConnectionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# DeleteConnectionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | \ No newline at end of file diff --git a/platform/docs/models/operations/deletewebhookconsumerrequest.md b/platform/docs/models/operations/deletewebhookconsumerrequest.md index f024c5e52..df64ea4d4 100644 --- a/platform/docs/models/operations/deletewebhookconsumerrequest.md +++ b/platform/docs/models/operations/deletewebhookconsumerrequest.md @@ -1,8 +1,8 @@ -# DeleteWebhookConsumerRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------- | ------------------------------------------- | ------------------------------------------- | ------------------------------------------- | ------------------------------------------- | +# DeleteWebhookConsumerRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------- | ------------------------------------------- | ------------------------------------------- | ------------------------------------------- | ------------------------------------------- | | `webhook_id` | *str* | :heavy_check_mark: | Unique identifier for the webhook consumer. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/platform/docs/models/operations/getcompanyaccesstokenrequest.md b/platform/docs/models/operations/getcompanyaccesstokenrequest.md index 255289cd1..7d5ca4902 100644 --- a/platform/docs/models/operations/getcompanyaccesstokenrequest.md +++ b/platform/docs/models/operations/getcompanyaccesstokenrequest.md @@ -1,8 +1,8 @@ -# GetCompanyAccessTokenRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# GetCompanyAccessTokenRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/platform/docs/models/operations/getcompanydatastatusrequest.md b/platform/docs/models/operations/getcompanydatastatusrequest.md index 5df9c3c5b..423c33d8a 100644 --- a/platform/docs/models/operations/getcompanydatastatusrequest.md +++ b/platform/docs/models/operations/getcompanydatastatusrequest.md @@ -1,8 +1,8 @@ -# GetCompanyDataStatusRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# GetCompanyDataStatusRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/platform/docs/models/operations/getcompanypushhistoryrequest.md b/platform/docs/models/operations/getcompanypushhistoryrequest.md index 385d11ce6..742e6f8b8 100644 --- a/platform/docs/models/operations/getcompanypushhistoryrequest.md +++ b/platform/docs/models/operations/getcompanypushhistoryrequest.md @@ -1,12 +1,12 @@ -# GetCompanyPushHistoryRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | -| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | -| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | +# GetCompanyPushHistoryRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | +| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | +| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | | `query` | *Optional[str]* | :heavy_minus_sign: | Codat query string. [Read more](https://docs.codat.io/using-the-api/querying). | id=e3334455-1aed-4e71-ab43-6bccf12092ee | \ No newline at end of file diff --git a/platform/docs/models/operations/getcompanyrequest.md b/platform/docs/models/operations/getcompanyrequest.md index 240b811b6..295378c0b 100644 --- a/platform/docs/models/operations/getcompanyrequest.md +++ b/platform/docs/models/operations/getcompanyrequest.md @@ -1,8 +1,8 @@ -# GetCompanyRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# GetCompanyRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/platform/docs/models/operations/getcompanysyncsettingsrequest.md b/platform/docs/models/operations/getcompanysyncsettingsrequest.md index 4641d8719..f90de688f 100644 --- a/platform/docs/models/operations/getcompanysyncsettingsrequest.md +++ b/platform/docs/models/operations/getcompanysyncsettingsrequest.md @@ -1,8 +1,8 @@ -# GetCompanySyncSettingsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# GetCompanySyncSettingsRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/platform/docs/models/operations/getconnectionmanagementaccesstokenrequest.md b/platform/docs/models/operations/getconnectionmanagementaccesstokenrequest.md index cd8b86c59..498c2b2da 100644 --- a/platform/docs/models/operations/getconnectionmanagementaccesstokenrequest.md +++ b/platform/docs/models/operations/getconnectionmanagementaccesstokenrequest.md @@ -1,8 +1,8 @@ -# GetConnectionManagementAccessTokenRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# GetConnectionManagementAccessTokenRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/platform/docs/models/operations/getconnectionrequest.md b/platform/docs/models/operations/getconnectionrequest.md index 6e9f3d18b..61c906783 100644 --- a/platform/docs/models/operations/getconnectionrequest.md +++ b/platform/docs/models/operations/getconnectionrequest.md @@ -1,9 +1,9 @@ -# GetConnectionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# GetConnectionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | \ No newline at end of file diff --git a/platform/docs/models/operations/getcreateupdatemodeloptionsbydatatyperequest.md b/platform/docs/models/operations/getcreateupdatemodeloptionsbydatatyperequest.md index a359134d2..cc6dd76d4 100644 --- a/platform/docs/models/operations/getcreateupdatemodeloptionsbydatatyperequest.md +++ b/platform/docs/models/operations/getcreateupdatemodeloptionsbydatatyperequest.md @@ -1,10 +1,10 @@ -# GetCreateUpdateModelOptionsByDataTypeRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +# GetCreateUpdateModelOptionsByDataTypeRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | | `data_type` | [shared.SchemaDataType](../../models/shared/schemadatatype.md) | :heavy_check_mark: | The key of a Codat data type. | invoices | \ No newline at end of file diff --git a/platform/docs/models/operations/getcustomdatatypeconfigurationrequest.md b/platform/docs/models/operations/getcustomdatatypeconfigurationrequest.md index 3b0da743e..a426afd00 100644 --- a/platform/docs/models/operations/getcustomdatatypeconfigurationrequest.md +++ b/platform/docs/models/operations/getcustomdatatypeconfigurationrequest.md @@ -1,9 +1,9 @@ -# GetCustomDataTypeConfigurationRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | -| `custom_data_identifier` | *str* | :heavy_check_mark: | Unique identifier for a custom data type. | DynamicsPurchaseOrders | +# GetCustomDataTypeConfigurationRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `custom_data_identifier` | *str* | :heavy_check_mark: | Unique identifier for a custom data type. | DynamicsPurchaseOrders | | `platform_key` | *str* | :heavy_check_mark: | A unique 4-letter key to represent a platform in each integration. | gbol | \ No newline at end of file diff --git a/platform/docs/models/operations/getintegrationrequest.md b/platform/docs/models/operations/getintegrationrequest.md index e5f10d9ee..dc4994e3b 100644 --- a/platform/docs/models/operations/getintegrationrequest.md +++ b/platform/docs/models/operations/getintegrationrequest.md @@ -1,8 +1,8 @@ -# GetIntegrationRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +# GetIntegrationRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | | `platform_key` | *str* | :heavy_check_mark: | A unique 4-letter key to represent a platform in each integration. | gbol | \ No newline at end of file diff --git a/platform/docs/models/operations/getintegrationsbrandingrequest.md b/platform/docs/models/operations/getintegrationsbrandingrequest.md index 09a308fb5..63faf59ed 100644 --- a/platform/docs/models/operations/getintegrationsbrandingrequest.md +++ b/platform/docs/models/operations/getintegrationsbrandingrequest.md @@ -1,8 +1,8 @@ -# GetIntegrationsBrandingRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +# GetIntegrationsBrandingRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | | `platform_key` | *str* | :heavy_check_mark: | A unique 4-letter key to represent a platform in each integration. | gbol | \ No newline at end of file diff --git a/platform/docs/models/operations/getpulloperationrequest.md b/platform/docs/models/operations/getpulloperationrequest.md index d2382bd6c..5bd36aa3e 100644 --- a/platform/docs/models/operations/getpulloperationrequest.md +++ b/platform/docs/models/operations/getpulloperationrequest.md @@ -1,9 +1,9 @@ -# GetPullOperationRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# GetPullOperationRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `dataset_id` | *str* | :heavy_check_mark: | Unique identifier for the dataset that completed its sync. | | \ No newline at end of file diff --git a/platform/docs/models/operations/getpushoperationrequest.md b/platform/docs/models/operations/getpushoperationrequest.md index d667790b5..4172a7b03 100644 --- a/platform/docs/models/operations/getpushoperationrequest.md +++ b/platform/docs/models/operations/getpushoperationrequest.md @@ -1,9 +1,9 @@ -# GetPushOperationRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# GetPushOperationRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `push_operation_key` | *str* | :heavy_check_mark: | Push operation key. | | \ No newline at end of file diff --git a/platform/docs/models/operations/getreadvalidationresultsrequest.md b/platform/docs/models/operations/getreadvalidationresultsrequest.md index b9d02033e..eb79d743f 100644 --- a/platform/docs/models/operations/getreadvalidationresultsrequest.md +++ b/platform/docs/models/operations/getreadvalidationresultsrequest.md @@ -1,9 +1,9 @@ -# GetReadValidationResultsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# GetReadValidationResultsRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `dataset_id` | *str* | :heavy_check_mark: | Unique identifier for the dataset that completed its sync. | | \ No newline at end of file diff --git a/platform/docs/models/operations/getsupplementaldataconfigurationrequest.md b/platform/docs/models/operations/getsupplementaldataconfigurationrequest.md index 6979a8eb8..864014b5c 100644 --- a/platform/docs/models/operations/getsupplementaldataconfigurationrequest.md +++ b/platform/docs/models/operations/getsupplementaldataconfigurationrequest.md @@ -1,9 +1,9 @@ -# GetSupplementalDataConfigurationRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `data_type` | [operations.PathParamDataType](../../models/operations/pathparamdatatype.md) | :heavy_check_mark: | Supported supplemental data data type. | invoices | -| `platform_key` | *str* | :heavy_check_mark: | A unique 4-letter key to represent a platform in each integration. | gbol | \ No newline at end of file +# GetSupplementalDataConfigurationRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `data_type` | *str* | :heavy_check_mark: | Supported supplemental data data type. | invoices | +| `platform_key` | *str* | :heavy_check_mark: | A unique 4-letter key to represent a platform in each integration. | gbol | \ No newline at end of file diff --git a/platform/docs/models/operations/listcompaniesrequest.md b/platform/docs/models/operations/listcompaniesrequest.md index 25cc480a0..e43853f9f 100644 --- a/platform/docs/models/operations/listcompaniesrequest.md +++ b/platform/docs/models/operations/listcompaniesrequest.md @@ -1,12 +1,12 @@ -# ListCompaniesRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | -| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | -| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | -| `query` | *Optional[str]* | :heavy_minus_sign: | Codat query string. [Read more](https://docs.codat.io/using-the-api/querying). | id=e3334455-1aed-4e71-ab43-6bccf12092ee | +# ListCompaniesRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | +| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | +| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | +| `query` | *Optional[str]* | :heavy_minus_sign: | Codat query string. [Read more](https://docs.codat.io/using-the-api/querying). | id=e3334455-1aed-4e71-ab43-6bccf12092ee | | `tags` | *Optional[str]* | :heavy_minus_sign: | Filter companies by tags using the "equals" (=), "not equals" (!=), and "contains" (~) operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying). | region=uk && team=invoice-finance | \ No newline at end of file diff --git a/platform/docs/models/operations/listconnectionsrequest.md b/platform/docs/models/operations/listconnectionsrequest.md index 949d3e3b6..0a3173fc6 100644 --- a/platform/docs/models/operations/listconnectionsrequest.md +++ b/platform/docs/models/operations/listconnectionsrequest.md @@ -1,12 +1,12 @@ -# ListConnectionsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | -| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | -| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | +# ListConnectionsRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | +| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | +| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | | `query` | *Optional[str]* | :heavy_minus_sign: | Codat query string. [Read more](https://docs.codat.io/using-the-api/querying). | id=e3334455-1aed-4e71-ab43-6bccf12092ee | \ No newline at end of file diff --git a/platform/docs/models/operations/listcustomdatatyperecordsrequest.md b/platform/docs/models/operations/listcustomdatatyperecordsrequest.md index 7a1f78a73..81839fc56 100644 --- a/platform/docs/models/operations/listcustomdatatyperecordsrequest.md +++ b/platform/docs/models/operations/listcustomdatatyperecordsrequest.md @@ -1,12 +1,12 @@ -# ListCustomDataTypeRecordsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `custom_data_identifier` | *str* | :heavy_check_mark: | Unique identifier for a custom data type. | DynamicsPurchaseOrders | -| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | +# ListCustomDataTypeRecordsRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `custom_data_identifier` | *str* | :heavy_check_mark: | Unique identifier for a custom data type. | DynamicsPurchaseOrders | +| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | | `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | \ No newline at end of file diff --git a/platform/docs/models/operations/listintegrationsrequest.md b/platform/docs/models/operations/listintegrationsrequest.md index fd8070b1e..876edc20b 100644 --- a/platform/docs/models/operations/listintegrationsrequest.md +++ b/platform/docs/models/operations/listintegrationsrequest.md @@ -1,11 +1,11 @@ -# ListIntegrationsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | -| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | -| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | +# ListIntegrationsRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | +| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | +| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | | `query` | *Optional[str]* | :heavy_minus_sign: | Codat query string. [Read more](https://docs.codat.io/using-the-api/querying). | id=e3334455-1aed-4e71-ab43-6bccf12092ee | \ No newline at end of file diff --git a/platform/docs/models/operations/listpulloperationsrequest.md b/platform/docs/models/operations/listpulloperationsrequest.md index 90a05e642..af69d3d64 100644 --- a/platform/docs/models/operations/listpulloperationsrequest.md +++ b/platform/docs/models/operations/listpulloperationsrequest.md @@ -1,12 +1,12 @@ -# ListPullOperationsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | -| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | -| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | +# ListPullOperationsRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | +| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | +| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | | `query` | *Optional[str]* | :heavy_minus_sign: | Codat query string. [Read more](https://docs.codat.io/using-the-api/querying). | id=e3334455-1aed-4e71-ab43-6bccf12092ee | \ No newline at end of file diff --git a/platform/docs/models/operations/pathparamdatatype.md b/platform/docs/models/operations/pathparamdatatype.md index baf6321fc..a7097b85d 100644 --- a/platform/docs/models/operations/pathparamdatatype.md +++ b/platform/docs/models/operations/pathparamdatatype.md @@ -1,38 +1,36 @@ -# PathParamDataType - -Data types that support supplemental data - -## Example Usage - -```python -from codat_platform.models.operations import PathParamDataType - -value = PathParamDataType.CHART_OF_ACCOUNTS -``` - - -## Values - -| Name | Value | -| ----------------------------- | ----------------------------- | -| `CHART_OF_ACCOUNTS` | chartOfAccounts | -| `BILLS` | bills | -| `COMPANY` | company | -| `CREDIT_NOTES` | creditNotes | -| `CUSTOMERS` | customers | -| `INVOICES` | invoices | -| `ITEMS` | items | -| `JOURNAL_ENTRIES` | journalEntries | -| `SUPPLIERS` | suppliers | -| `TAX_RATES` | taxRates | -| `COMMERCE_COMPANY_INFO` | commerce-companyInfo | -| `COMMERCE_CUSTOMERS` | commerce-customers | -| `COMMERCE_DISPUTES` | commerce-disputes | -| `COMMERCE_LOCATIONS` | commerce-locations | -| `COMMERCE_ORDERS` | commerce-orders | -| `COMMERCE_PAYMENTS` | commerce-payments | -| `COMMERCE_PAYMENT_METHODS` | commerce-paymentMethods | -| `COMMERCE_PRODUCTS` | commerce-products | -| `COMMERCE_PRODUCT_CATEGORIES` | commerce-productCategories | -| `COMMERCE_TAX_COMPONENTS` | commerce-taxComponents | +# PathParamDataType + +## Example Usage + +```python +from codat_platform.models.operations import PathParamDataType + +value = PathParamDataType.CHART_OF_ACCOUNTS +``` + + +## Values + +| Name | Value | +| ----------------------------- | ----------------------------- | +| `CHART_OF_ACCOUNTS` | chartOfAccounts | +| `BILLS` | bills | +| `COMPANY` | company | +| `CREDIT_NOTES` | creditNotes | +| `CUSTOMERS` | customers | +| `INVOICES` | invoices | +| `ITEMS` | items | +| `JOURNAL_ENTRIES` | journalEntries | +| `SUPPLIERS` | suppliers | +| `TAX_RATES` | taxRates | +| `COMMERCE_COMPANY_INFO` | commerce-companyInfo | +| `COMMERCE_CUSTOMERS` | commerce-customers | +| `COMMERCE_DISPUTES` | commerce-disputes | +| `COMMERCE_LOCATIONS` | commerce-locations | +| `COMMERCE_ORDERS` | commerce-orders | +| `COMMERCE_PAYMENTS` | commerce-payments | +| `COMMERCE_PAYMENT_METHODS` | commerce-paymentMethods | +| `COMMERCE_PRODUCTS` | commerce-products | +| `COMMERCE_PRODUCT_CATEGORIES` | commerce-productCategories | +| `COMMERCE_TAX_COMPONENTS` | commerce-taxComponents | | `COMMERCE_TRANSACTIONS` | commerce-transactions | \ No newline at end of file diff --git a/platform/docs/models/operations/refreshcompanydatarequest.md b/platform/docs/models/operations/refreshcompanydatarequest.md index 73f8e3d12..4d379960c 100644 --- a/platform/docs/models/operations/refreshcompanydatarequest.md +++ b/platform/docs/models/operations/refreshcompanydatarequest.md @@ -1,8 +1,8 @@ -# RefreshCompanyDataRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# RefreshCompanyDataRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/platform/docs/models/operations/refreshcustomdatatyperequest.md b/platform/docs/models/operations/refreshcustomdatatyperequest.md index 3308755d8..996114b7c 100644 --- a/platform/docs/models/operations/refreshcustomdatatyperequest.md +++ b/platform/docs/models/operations/refreshcustomdatatyperequest.md @@ -1,10 +1,10 @@ -# RefreshCustomDataTypeRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------- | ----------------------------------------- | ----------------------------------------- | ----------------------------------------- | ----------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +# RefreshCustomDataTypeRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------- | ----------------------------------------- | ----------------------------------------- | ----------------------------------------- | ----------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | | `custom_data_identifier` | *str* | :heavy_check_mark: | Unique identifier for a custom data type. | DynamicsPurchaseOrders | \ No newline at end of file diff --git a/platform/docs/models/operations/refreshdatatyperequest.md b/platform/docs/models/operations/refreshdatatyperequest.md index 5b2ba9c29..73c85965e 100644 --- a/platform/docs/models/operations/refreshdatatyperequest.md +++ b/platform/docs/models/operations/refreshdatatyperequest.md @@ -1,10 +1,10 @@ -# RefreshDataTypeRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *Optional[str]* | :heavy_minus_sign: | Optionally, provide a data connection id to only queue pull operations on that connection. | | +# RefreshDataTypeRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *Optional[str]* | :heavy_minus_sign: | Optionally, provide a data connection id to only queue pull operations on that connection. | | | `data_type` | [shared.SchemaDataType](../../models/shared/schemadatatype.md) | :heavy_check_mark: | The key of a Codat data type. | invoices | \ No newline at end of file diff --git a/platform/docs/models/operations/refreshproductdatarequest.md b/platform/docs/models/operations/refreshproductdatarequest.md index a473e0460..036441116 100644 --- a/platform/docs/models/operations/refreshproductdatarequest.md +++ b/platform/docs/models/operations/refreshproductdatarequest.md @@ -1,10 +1,10 @@ -# RefreshProductDataRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `request_body` | [Optional[operations.RefreshProductDataRequestBody]](../../models/operations/refreshproductdatarequestbody.md) | :heavy_minus_sign: | Optionally specify one or more data types to refresh for the given custom product. If omitted, the product's scheduled refresh is triggered as usual. When provided, each data type must be valid for the specified product. | | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# RefreshProductDataRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `request_body` | [Optional[operations.RefreshProductDataRequestBody]](../../models/operations/refreshproductdatarequestbody.md) | :heavy_minus_sign: | Optionally specify one or more data types to refresh for the given custom product. If omitted, the product's scheduled refresh is triggered as usual. When provided, each data type must be valid for the specified product. | | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `product_identifier` | *str* | :heavy_check_mark: | Human-readable product identifier for a product. | **Example 1:** bank-feeds
**Example 2:** lending
**Example 3:** payables
**Example 4:** expenses | \ No newline at end of file diff --git a/platform/docs/models/operations/refreshproductdatarequestbody.md b/platform/docs/models/operations/refreshproductdatarequestbody.md index 2e1a7c868..9f5a7beb3 100644 --- a/platform/docs/models/operations/refreshproductdatarequestbody.md +++ b/platform/docs/models/operations/refreshproductdatarequestbody.md @@ -1,10 +1,9 @@ -# RefreshProductDataRequestBody - -Optionally specify one or more data types to refresh for the given custom product. If omitted, the product's scheduled refresh is triggered as usual. When provided, each data type must be valid for the specified product. - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | +# RefreshProductDataRequestBody + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | | `data_types` | List[*str*] | :heavy_minus_sign: | One or more data types to refresh for the product. | \ No newline at end of file diff --git a/platform/docs/models/operations/removeproductrequest.md b/platform/docs/models/operations/removeproductrequest.md index 1e8165b51..66ea6ee17 100644 --- a/platform/docs/models/operations/removeproductrequest.md +++ b/platform/docs/models/operations/removeproductrequest.md @@ -1,9 +1,9 @@ -# RemoveProductRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# RemoveProductRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `product_identifier` | *str* | :heavy_check_mark: | Human-readable product identifier for a product. | **Example 1:** bank-feeds
**Example 2:** lending
**Example 3:** payables
**Example 4:** expenses | \ No newline at end of file diff --git a/platform/docs/models/operations/replacecompanyrequest.md b/platform/docs/models/operations/replacecompanyrequest.md index cde3d20e3..2b90faf30 100644 --- a/platform/docs/models/operations/replacecompanyrequest.md +++ b/platform/docs/models/operations/replacecompanyrequest.md @@ -1,9 +1,9 @@ -# ReplaceCompanyRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -| `company_request_body` | [Optional[shared.CompanyRequestBody]](../../models/shared/companyrequestbody.md) | :heavy_minus_sign: | N/A | | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file +# ReplaceCompanyRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `company_request_body` | [Optional[shared.CompanyRequestBody]](../../models/shared/companyrequestbody.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/operations/setcompanysyncsettingsrequest.md b/platform/docs/models/operations/setcompanysyncsettingsrequest.md index e3d16ecc0..8c8830c2c 100644 --- a/platform/docs/models/operations/setcompanysyncsettingsrequest.md +++ b/platform/docs/models/operations/setcompanysyncsettingsrequest.md @@ -1,9 +1,9 @@ -# SetCompanySyncSettingsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `request_body` | [Optional[operations.SetCompanySyncSettingsRequestBody]](../../models/operations/setcompanysyncsettingsrequestbody.md) | :heavy_minus_sign: | Include a `syncSetting` object for each data type.
`syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them. | | +# SetCompanySyncSettingsRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `request_body` | [Optional[operations.SetCompanySyncSettingsRequestBody]](../../models/operations/setcompanysyncsettingsrequestbody.md) | :heavy_minus_sign: | Include a `syncSetting` object for each data type. `syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them. | | | `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/platform/docs/models/operations/setcompanysyncsettingsrequestbody.md b/platform/docs/models/operations/setcompanysyncsettingsrequestbody.md index 4ac10a348..62252e382 100644 --- a/platform/docs/models/operations/setcompanysyncsettingsrequestbody.md +++ b/platform/docs/models/operations/setcompanysyncsettingsrequestbody.md @@ -1,13 +1,10 @@ -# SetCompanySyncSettingsRequestBody - -Include a `syncSetting` object for each data type. -`syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them. - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `overrides_defaults` | *Optional[bool]* | :heavy_minus_sign: | Set to `True` if you want to override default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings). | | +# SetCompanySyncSettingsRequestBody + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `overrides_defaults` | *Optional[bool]* | :heavy_minus_sign: | Set to `True` if you want to override default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings). | | | `settings` | List[[shared.SyncSetting](../../models/shared/syncsetting.md)] | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/operations/setconnectionmanagementcorssettingsrequest.md b/platform/docs/models/operations/setconnectionmanagementcorssettingsrequest.md new file mode 100644 index 000000000..108e88ab3 --- /dev/null +++ b/platform/docs/models/operations/setconnectionmanagementcorssettingsrequest.md @@ -0,0 +1,8 @@ +# SetConnectionManagementCorsSettingsRequest + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `connection_management_allowed_origins` | [Optional[shared.ConnectionManagementAllowedOrigins]](../../models/shared/connectionmanagementallowedorigins.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/operations/setcorssettingsrequest.md b/platform/docs/models/operations/setcorssettingsrequest.md new file mode 100644 index 000000000..ff2d6d4a0 --- /dev/null +++ b/platform/docs/models/operations/setcorssettingsrequest.md @@ -0,0 +1,8 @@ +# SetCorsSettingsRequest + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `connection_management_allowed_origins` | [Optional[shared.ConnectionManagementAllowedOrigins]](../../models/shared/connectionmanagementallowedorigins.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/operations/unlinkconnectionrequest.md b/platform/docs/models/operations/unlinkconnectionrequest.md index b96501797..83e2b0779 100644 --- a/platform/docs/models/operations/unlinkconnectionrequest.md +++ b/platform/docs/models/operations/unlinkconnectionrequest.md @@ -1,10 +1,10 @@ -# UnlinkConnectionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `update_connection_status` | [Optional[shared.UpdateConnectionStatus]](../../models/shared/updateconnectionstatus.md) | :heavy_minus_sign: | N/A | | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | \ No newline at end of file +# UnlinkConnectionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `update_connection_status` | [Optional[shared.UpdateConnectionStatus]](../../models/shared/updateconnectionstatus.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/operations/updatecompanyrequest.md b/platform/docs/models/operations/updatecompanyrequest.md index 47802c383..9718e2ff6 100644 --- a/platform/docs/models/operations/updatecompanyrequest.md +++ b/platform/docs/models/operations/updatecompanyrequest.md @@ -1,9 +1,9 @@ -# UpdateCompanyRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `company_update_request` | [Optional[shared.CompanyUpdateRequest]](../../models/shared/companyupdaterequest.md) | :heavy_minus_sign: | N/A | | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file +# UpdateCompanyRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `company_update_request` | [Optional[shared.CompanyUpdateRequest]](../../models/shared/companyupdaterequest.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/operations/updateconnectionauthorizationrequest.md b/platform/docs/models/operations/updateconnectionauthorizationrequest.md index f35cc6013..c33224923 100644 --- a/platform/docs/models/operations/updateconnectionauthorizationrequest.md +++ b/platform/docs/models/operations/updateconnectionauthorizationrequest.md @@ -1,10 +1,10 @@ -# UpdateConnectionAuthorizationRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | -| `request_body` | Dict[str, *str*] | :heavy_minus_sign: | N/A | | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# UpdateConnectionAuthorizationRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +| `request_body` | Dict[str, *str*] | :heavy_minus_sign: | N/A | | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | \ No newline at end of file diff --git a/platform/docs/models/operations/updateprofilerequest.md b/platform/docs/models/operations/updateprofilerequest.md new file mode 100644 index 000000000..856a20d9e --- /dev/null +++ b/platform/docs/models/operations/updateprofilerequest.md @@ -0,0 +1,8 @@ +# UpdateProfileRequest + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | +| `profile` | [Optional[shared.Profile]](../../models/shared/profile.md) | :heavy_minus_sign: | All fields should be included when updating your profile. | \ No newline at end of file diff --git a/platform/docs/models/operations/updateprofilesyncsettingsrequest.md b/platform/docs/models/operations/updateprofilesyncsettingsrequest.md new file mode 100644 index 000000000..8dcc8e0e9 --- /dev/null +++ b/platform/docs/models/operations/updateprofilesyncsettingsrequest.md @@ -0,0 +1,8 @@ +# UpdateProfileSyncSettingsRequest + + +## Fields + +| Field | Type | Required | Description | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `update_profile_sync_settings_request` | [Optional[shared.UpdateProfileSyncSettingsRequest]](../../models/shared/updateprofilesyncsettingsrequest.md) | :heavy_minus_sign: | Include a `syncSetting` object for each data type. `syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them. | \ No newline at end of file diff --git a/platform/docs/models/operations/updateprofilesyncsettingsrequestbody.md b/platform/docs/models/operations/updateprofilesyncsettingsrequestbody.md index 50e12a24f..4215ac588 100644 --- a/platform/docs/models/operations/updateprofilesyncsettingsrequestbody.md +++ b/platform/docs/models/operations/updateprofilesyncsettingsrequestbody.md @@ -1,13 +1,7 @@ -# UpdateProfileSyncSettingsRequestBody - -Include a `syncSetting` object for each data type. -`syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them. - - -## Fields - -| Field | Type | Required | Description | -| --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | -| `client_id` | *str* | :heavy_check_mark: | Unique identifier for your client in Codat. | -| `overrides_defaults` | *Optional[bool]* | :heavy_minus_sign: | Set to `True` if you want to override default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings). | -| `settings` | List[[shared.SyncSetting](../../models/shared/syncsetting.md)] | :heavy_check_mark: | N/A | \ No newline at end of file +# UpdateProfileSyncSettingsRequestBody + + +## Fields + +| Field | Type | Required | Description | +| ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/platform/docs/models/shared/accesstoken.md b/platform/docs/models/shared/accesstoken.md new file mode 100644 index 000000000..c159a6812 --- /dev/null +++ b/platform/docs/models/shared/accesstoken.md @@ -0,0 +1,10 @@ +# AccessToken + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| `access_token` | *str* | :heavy_check_mark: | The access token for the company. | | +| `expires_in` | *int* | :heavy_check_mark: | The number of seconds until the access token expires. | 86400 | +| `token_type` | *str* | :heavy_check_mark: | The type of token. | Bearer | \ No newline at end of file diff --git a/platform/docs/models/shared/apikeydetails.md b/platform/docs/models/shared/apikeydetails.md index f7bd9136a..89aa5333b 100644 --- a/platform/docs/models/shared/apikeydetails.md +++ b/platform/docs/models/shared/apikeydetails.md @@ -1,13 +1,13 @@ -# APIKeyDetails - -Details of the API key. - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `api_key` | *Optional[str]* | :heavy_minus_sign: | The API key value used to make authenticated http requests. | ztHQGvnC4XN2CgUhaDWEG4ySLUJqWjp7zkbZkGHd | -| `created_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the API key. | e288a972-b402-4b21-93f9-b5335ae5679c | +# APIKeyDetails + +Details of the API key. + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `api_key` | *Optional[str]* | :heavy_minus_sign: | The API key value used to make authenticated http requests. | ztHQGvnC4XN2CgUhaDWEG4ySLUJqWjp7zkbZkGHd | +| `created_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the API key. | e288a972-b402-4b21-93f9-b5335ae5679c | | `name` | *OptionalNullable[str]* | :heavy_minus_sign: | A meaningful name assigned to the API key. | azure-invoice-finance-processor | \ No newline at end of file diff --git a/platform/docs/models/shared/apikeys.md b/platform/docs/models/shared/apikeys.md index 600de97bc..55844d4fc 100644 --- a/platform/docs/models/shared/apikeys.md +++ b/platform/docs/models/shared/apikeys.md @@ -1,8 +1,8 @@ -# APIKeys - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +# APIKeys + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | `results` | List[[Nullable[shared.APIKeyDetails]](../../models/shared/apikeydetails.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/branding.md b/platform/docs/models/shared/branding.md index c7f07b1dc..e8b5f33e5 100644 --- a/platform/docs/models/shared/branding.md +++ b/platform/docs/models/shared/branding.md @@ -1,10 +1,10 @@ -# Branding - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `button` | [Optional[shared.BrandingButton]](../../models/shared/brandingbutton.md) | :heavy_minus_sign: | Button branding references. | | -| `logo` | [Optional[shared.BrandingLogo]](../../models/shared/brandinglogo.md) | :heavy_minus_sign: | Logo branding references. | | +# Branding + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `button` | [Optional[shared.BrandingButton]](../../models/shared/brandingbutton.md) | :heavy_minus_sign: | Button branding references. | | +| `logo` | [Optional[shared.BrandingLogo]](../../models/shared/brandinglogo.md) | :heavy_minus_sign: | Logo branding references. | | | `source_id` | *Optional[str]* | :heavy_minus_sign: | A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`. | 35b92968-9851-4095-ad60-395c95cbcba4 | \ No newline at end of file diff --git a/platform/docs/models/shared/brandingbutton.md b/platform/docs/models/shared/brandingbutton.md index b1f2fc046..2c079b368 100644 --- a/platform/docs/models/shared/brandingbutton.md +++ b/platform/docs/models/shared/brandingbutton.md @@ -1,11 +1,9 @@ -# BrandingButton - -Button branding references. - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | -| `default` | [Optional[shared.BrandingImage]](../../models/shared/brandingimage.md) | :heavy_minus_sign: | N/A | +# BrandingButton + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `default` | [Optional[shared.BrandingImage]](../../models/shared/brandingimage.md) | :heavy_minus_sign: | N/A | | `hover` | [Optional[shared.BrandingImage]](../../models/shared/brandingimage.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/brandingimage.md b/platform/docs/models/shared/brandingimage.md index e62927204..882a7d405 100644 --- a/platform/docs/models/shared/brandingimage.md +++ b/platform/docs/models/shared/brandingimage.md @@ -1,8 +1,8 @@ -# BrandingImage - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +# BrandingImage + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | | `image` | [Optional[shared.ImageReference]](../../models/shared/imagereference.md) | :heavy_minus_sign: | Image reference. | \ No newline at end of file diff --git a/platform/docs/models/shared/brandinglogo.md b/platform/docs/models/shared/brandinglogo.md index d076810e6..ea8675ba5 100644 --- a/platform/docs/models/shared/brandinglogo.md +++ b/platform/docs/models/shared/brandinglogo.md @@ -1,11 +1,9 @@ -# BrandingLogo - -Logo branding references. - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | -| `full` | [Optional[shared.BrandingImage]](../../models/shared/brandingimage.md) | :heavy_minus_sign: | N/A | +# BrandingLogo + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `full` | [Optional[shared.BrandingImage]](../../models/shared/brandingimage.md) | :heavy_minus_sign: | N/A | | `square` | [Optional[shared.BrandingImage]](../../models/shared/brandingimage.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/clientratelimitwebhook.md b/platform/docs/models/shared/clientratelimitwebhook.md index 36e2030f0..8ecf1141e 100644 --- a/platform/docs/models/shared/clientratelimitwebhook.md +++ b/platform/docs/models/shared/clientratelimitwebhook.md @@ -1,11 +1,11 @@ -# ClientRateLimitWebhook - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | **Example 1:** client.rateLimit.reset
**Example 2:** client.rateLimit.reached | -| `generated_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the event. | 743ec94a-8aa4-44bb-8bd4-e1855ee0e74b | +# ClientRateLimitWebhook + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | **Example 1:** client.rateLimit.reset
**Example 2:** client.rateLimit.reached | +| `generated_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the event. | 743ec94a-8aa4-44bb-8bd4-e1855ee0e74b | | `payload` | [Optional[shared.ClientRateLimitWebhookPayload]](../../models/shared/clientratelimitwebhookpayload.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/shared/clientratelimitwebhookpayload.md b/platform/docs/models/shared/clientratelimitwebhookpayload.md index 41b82096c..ae6051b29 100644 --- a/platform/docs/models/shared/clientratelimitwebhookpayload.md +++ b/platform/docs/models/shared/clientratelimitwebhookpayload.md @@ -1,10 +1,10 @@ -# ClientRateLimitWebhookPayload - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `daily_quota` | *Optional[int]* | :heavy_minus_sign: | The number of available requests per day. | | -| `expiry_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +# ClientRateLimitWebhookPayload + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `daily_quota` | *Optional[int]* | :heavy_minus_sign: | The number of available requests per day. | | +| `expiry_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | | `quota_remaining` | *Optional[int]* | :heavy_minus_sign: | Total number of requests remaining for your client. | | \ No newline at end of file diff --git a/platform/docs/models/shared/companies.md b/platform/docs/models/shared/companies.md index 670c41db2..a4a43b1c2 100644 --- a/platform/docs/models/shared/companies.md +++ b/platform/docs/models/shared/companies.md @@ -1,12 +1,12 @@ -# Companies - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | -| `page_number` | *int* | :heavy_check_mark: | Current page number. | | -| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | -| `results` | List[[shared.Company](../../models/shared/company.md)] | :heavy_minus_sign: | N/A | | +# Companies + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | +| `page_number` | *int* | :heavy_check_mark: | Current page number. | | +| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | +| `results` | List[[shared.Company](../../models/shared/company.md)] | :heavy_minus_sign: | N/A | | | `total_results` | *int* | :heavy_check_mark: | Total number of items. | | \ No newline at end of file diff --git a/platform/docs/models/shared/company.md b/platform/docs/models/shared/company.md index 2b8a8ace7..3bcba3ada 100644 --- a/platform/docs/models/shared/company.md +++ b/platform/docs/models/shared/company.md @@ -1,25 +1,25 @@ -# Company - -In Codat, a company represents a business sharing access to their data. Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources such as one connection to [Xero](https://docs.codat.io/integrations/accounting/xero/accounting-xero) for accounting data, two connections to [Plaid](https://docs.codat.io/integrations/banking/plaid/banking-plaid) for two bank accounts and a connection to [Zettle](https://docs.codat.io/integrations/commerce/zettle/commerce-zettle) for POS data. - -Typically each company is one of your customers. - -When you create a company, you can specify a `name` and we will automatically generate a unique `id` for the company. You can also add a `description` to store any additional information about the company. - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `created` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `created_by_user_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of user that created the company in Codat. | | -| `data_connections` | List[[shared.Connection](../../models/shared/connection.md)] | :heavy_minus_sign: | N/A | | -| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | -| `id` | *str* | :heavy_check_mark: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `last_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `name` | *str* | :heavy_check_mark: | The name of the company | Codat Ltd. | -| `products` | List[*str*] | :heavy_minus_sign: | An array of products that are currently enabled for the company. | | -| `redirect` | *str* | :heavy_check_mark: | The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company. | https://link.codat.io/company/27628208-459c-46a2-a705-5641ce25f739 | -| `reference_parent_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | N/A | | -| `reference_subsidiary_companies` | List[[shared.CompanyReference](../../models/shared/companyreference.md)] | :heavy_minus_sign: | A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children. | | +# Company + +In Codat, a company represents a business sharing access to their data. Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources such as one connection to [Xero](https://docs.codat.io/integrations/accounting/xero/accounting-xero) for accounting data, two connections to [Plaid](https://docs.codat.io/integrations/banking/plaid/banking-plaid) for two bank accounts and a connection to [Zettle](https://docs.codat.io/integrations/commerce/zettle/commerce-zettle) for POS data. + +Typically each company is one of your customers. + +When you create a company, you can specify a `name` and we will automatically generate a unique `id` for the company. You can also add a `description` to store any additional information about the company. + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `created` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `created_by_user_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of user that created the company in Codat. | | +| `data_connections` | List[[shared.Connection](../../models/shared/connection.md)] | :heavy_minus_sign: | N/A | | +| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | +| `id` | *str* | :heavy_check_mark: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `last_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `name` | *str* | :heavy_check_mark: | The name of the company | Codat Ltd. | +| `products` | List[*str*] | :heavy_minus_sign: | An array of products that are currently enabled for the company. | | +| `redirect` | *str* | :heavy_check_mark: | The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company. | https://link.codat.io/company/27628208-459c-46a2-a705-5641ce25f739 | +| `reference_parent_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | The parent entity or controlling organization of this company. Null if the company has no parent. | | +| `reference_subsidiary_companies` | List[[shared.CompanyReference](../../models/shared/companyreference.md)] | :heavy_minus_sign: | A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children. | | | `tags` | Dict[str, *str*] | :heavy_minus_sign: | A collection of user-defined key-value pairs that store custom metadata against the company. | | \ No newline at end of file diff --git a/platform/docs/models/shared/companyaccesstoken.md b/platform/docs/models/shared/companyaccesstoken.md index a6304c6d3..fee04db9e 100644 --- a/platform/docs/models/shared/companyaccesstoken.md +++ b/platform/docs/models/shared/companyaccesstoken.md @@ -1,12 +1,12 @@ -# CompanyAccessToken - -Details of the access token provisioned for a company. - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | -| `access_token` | *str* | :heavy_check_mark: | The access token for the company. | | -| `expires_in` | *int* | :heavy_check_mark: | The number of seconds until the access token expires. | 86400 | +# CompanyAccessToken + +Details of the access token provisioned for a company. + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| `access_token` | *str* | :heavy_check_mark: | The access token for the company. | | +| `expires_in` | *int* | :heavy_check_mark: | The number of seconds until the access token expires. | 86400 | | `token_type` | *str* | :heavy_check_mark: | The type of token. | Bearer | \ No newline at end of file diff --git a/platform/docs/models/shared/companydetails.md b/platform/docs/models/shared/companydetails.md index 50c3eae38..18075d9dc 100644 --- a/platform/docs/models/shared/companydetails.md +++ b/platform/docs/models/shared/companydetails.md @@ -1,18 +1,18 @@ -# CompanyDetails - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `created` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `created_by_user_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of user that created the company in Codat. | | -| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | -| `id` | *str* | :heavy_check_mark: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `last_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `name` | *str* | :heavy_check_mark: | The name of the company | Codat Ltd. | -| `products` | List[*str*] | :heavy_minus_sign: | An array of products that are currently enabled for the company. | | -| `redirect` | *str* | :heavy_check_mark: | The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company. | https://link.codat.io/company/27628208-459c-46a2-a705-5641ce25f739 | -| `reference_parent_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | N/A | | -| `reference_subsidiary_companies` | List[[shared.CompanyReference](../../models/shared/companyreference.md)] | :heavy_minus_sign: | A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children. | | +# CompanyDetails + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `created` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `created_by_user_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of user that created the company in Codat. | | +| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | +| `id` | *str* | :heavy_check_mark: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `last_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `name` | *str* | :heavy_check_mark: | The name of the company | Codat Ltd. | +| `products` | List[*str*] | :heavy_minus_sign: | An array of products that are currently enabled for the company. | | +| `redirect` | *str* | :heavy_check_mark: | The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company. | https://link.codat.io/company/27628208-459c-46a2-a705-5641ce25f739 | +| `reference_parent_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | The parent entity or controlling organization of this company. Null if the company has no parent. | | +| `reference_subsidiary_companies` | List[[shared.CompanyReference](../../models/shared/companyreference.md)] | :heavy_minus_sign: | A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children. | | | `tags` | Dict[str, *str*] | :heavy_minus_sign: | A collection of user-defined key-value pairs that store custom metadata against the company. | | \ No newline at end of file diff --git a/platform/docs/models/shared/companyproductwebhook.md b/platform/docs/models/shared/companyproductwebhook.md new file mode 100644 index 000000000..c8fdddf71 --- /dev/null +++ b/platform/docs/models/shared/companyproductwebhook.md @@ -0,0 +1,11 @@ +# CompanyProductWebhook + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | **Example 1:** company.product.added
**Example 2:** company.product.removed | +| `generated_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the event. | ba29118f-5406-4e59-b05c-ba307ca38d01 | +| `payload` | [Optional[shared.CompanyProductWebhookPayload]](../../models/shared/companyproductwebhookpayload.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/shared/companyproductwebhookpayload.md b/platform/docs/models/shared/companyproductwebhookpayload.md new file mode 100644 index 000000000..1f7ff3147 --- /dev/null +++ b/platform/docs/models/shared/companyproductwebhookpayload.md @@ -0,0 +1,13 @@ +# CompanyProductWebhookPayload + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the company the product change applies to. | 0498e921-9b53-4396-a412-4f2f5983b0a2 | +| `name` | *Optional[str]* | :heavy_minus_sign: | Name of the company. | Bank of Dave | +| `product_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the product that was added to or removed from the company. | lending | +| `product_name` | *Optional[str]* | :heavy_minus_sign: | Name of the product that was added to or removed from the company. | Lending | +| `products` | List[*str*] | :heavy_minus_sign: | The full list of products currently enabled for the company. | [
"accounting",
"banking",
"lending"
] | \ No newline at end of file diff --git a/platform/docs/models/shared/companyreference.md b/platform/docs/models/shared/companyreference.md index b651f69d5..97b15c6bc 100644 --- a/platform/docs/models/shared/companyreference.md +++ b/platform/docs/models/shared/companyreference.md @@ -1,12 +1,12 @@ -# CompanyReference - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `links` | [Optional[shared.CompanyReferenceLinks]](../../models/shared/companyreferencelinks.md) | :heavy_minus_sign: | A collection of links for the company. | | -| `name` | *Optional[str]* | :heavy_minus_sign: | The name of the company | Codat Ltd. | +# CompanyReference + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `links` | [Optional[shared.CompanyReferenceLinks]](../../models/shared/companyreferencelinks.md) | :heavy_minus_sign: | A collection of links for the company. | | +| `name` | *Optional[str]* | :heavy_minus_sign: | The name of the company | Codat Ltd. | | `tags` | Dict[str, *str*] | :heavy_minus_sign: | A collection of user-defined key-value pairs that store custom metadata against the company. | | \ No newline at end of file diff --git a/platform/docs/models/shared/companyreferencelinks.md b/platform/docs/models/shared/companyreferencelinks.md index ee01fd320..a4c491724 100644 --- a/platform/docs/models/shared/companyreferencelinks.md +++ b/platform/docs/models/shared/companyreferencelinks.md @@ -1,10 +1,10 @@ -# CompanyReferenceLinks - -A collection of links for the company. - - -## Fields - -| Field | Type | Required | Description | -| --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | +# CompanyReferenceLinks + +A collection of links for the company. + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | | `portal` | *Optional[str]* | :heavy_minus_sign: | Link to the company page in the portal. | \ No newline at end of file diff --git a/platform/docs/models/shared/companyrequestbody.md b/platform/docs/models/shared/companyrequestbody.md index 3ae35b3c7..107790e6e 100644 --- a/platform/docs/models/shared/companyrequestbody.md +++ b/platform/docs/models/shared/companyrequestbody.md @@ -1,10 +1,10 @@ -# CompanyRequestBody - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | -| `name` | *str* | :heavy_check_mark: | Name of company being connected. | Bank of Dave | +# CompanyRequestBody + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | +| `name` | *str* | :heavy_check_mark: | Name of company being connected. | Bank of Dave | | `tags` | Dict[str, *str*] | :heavy_minus_sign: | A collection of user-defined key-value pairs that store custom metadata against the company. | | \ No newline at end of file diff --git a/platform/docs/models/shared/companysyncsettings.md b/platform/docs/models/shared/companysyncsettings.md index e7a225895..fff7a2521 100644 --- a/platform/docs/models/shared/companysyncsettings.md +++ b/platform/docs/models/shared/companysyncsettings.md @@ -1,10 +1,10 @@ -# CompanySyncSettings - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `overrides_defaults` | *Optional[bool]* | :heavy_minus_sign: | Set to `True` if you want to override the default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings). | | +# CompanySyncSettings + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `company_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `overrides_defaults` | *Optional[bool]* | :heavy_minus_sign: | Set to `True` if you want to override the default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings). | | | `settings` | List[[shared.SyncSetting](../../models/shared/syncsetting.md)] | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/shared/companyupdaterequest.md b/platform/docs/models/shared/companyupdaterequest.md index c79edb11b..1ae031209 100644 --- a/platform/docs/models/shared/companyupdaterequest.md +++ b/platform/docs/models/shared/companyupdaterequest.md @@ -1,10 +1,10 @@ -# CompanyUpdateRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | -| `name` | *Optional[str]* | :heavy_minus_sign: | Name of company being connected. | Bank of Dave | +# CompanyUpdateRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | +| `name` | *Optional[str]* | :heavy_minus_sign: | Name of company being connected. | Bank of Dave | | `tags` | Dict[str, *str*] | :heavy_minus_sign: | A collection of user-defined key-value pairs that store custom metadata against the company. | | \ No newline at end of file diff --git a/platform/docs/models/shared/companywebhook.md b/platform/docs/models/shared/companywebhook.md index 304b4451b..819edb0bb 100644 --- a/platform/docs/models/shared/companywebhook.md +++ b/platform/docs/models/shared/companywebhook.md @@ -1,11 +1,11 @@ -# CompanyWebhook - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | **Example 1:** company.created
**Example 2:** company.deleted | -| `generated_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the event | ba29118f-5406-4e59-b05c-ba307ca38d01 | +# CompanyWebhook + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | **Example 1:** company.created
**Example 2:** company.deleted | +| `generated_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the event | ba29118f-5406-4e59-b05c-ba307ca38d01 | | `payload` | [Optional[shared.CompanyDetails]](../../models/shared/companydetails.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/shared/connection.md b/platform/docs/models/shared/connection.md index 2817473cc..82db537f0 100644 --- a/platform/docs/models/shared/connection.md +++ b/platform/docs/models/shared/connection.md @@ -1,30 +1,31 @@ -# Connection - -A connection represents a [company's](https://docs.codat.io/platform-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source. - -A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to: - -- [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection. -- [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections. -- [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections. -Any combination of accounting, banking, and commerce data connections is allowed. - -Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `connection_info` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | | -| `created` | *str* | :heavy_check_mark: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `data_connection_errors` | List[[shared.DataConnectionError](../../models/shared/dataconnectionerror.md)] | :heavy_minus_sign: | N/A | | -| `id` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `integration_id` | *str* | :heavy_check_mark: | A Codat ID representing the integration. | fd321cb6-7963-4506-b873-e99593a45e30 | -| `integration_key` | *Optional[str]* | :heavy_minus_sign: | A unique four-character ID that identifies the platform of the company's data connection. This ensures continuity if the platform changes its name in the future. | | -| `last_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `link_url` | *str* | :heavy_check_mark: | The link URL your customers can use to authorize access to their business application. | https://link-api.codat.io/companies/86bd88cb-44ab-4dfb-b32f-87b19b14287f/connections/2e2eb431-c1fa-4dc9-93fa-d29781c12bcd/start | -| `platform_name` | *str* | :heavy_check_mark: | Name of integration connected to company. | | -| `source_id` | *str* | :heavy_check_mark: | A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`. | 35b92968-9851-4095-ad60-395c95cbcba4 | -| `source_type` | [shared.SourceType](../../models/shared/sourcetype.md) | :heavy_check_mark: | The type of platform of the connection. | Accounting | +# Connection + +A connection represents a [company's](https://docs.codat.io/platform-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source. + +A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to: + +- [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection. +- [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections. +- [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections. +Any combination of accounting, banking, and commerce data connections is allowed. + +Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | | +| `connection_info` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | | +| `created` | *str* | :heavy_check_mark: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `data_connection_errors` | List[[shared.DataConnectionError](../../models/shared/dataconnectionerror.md)] | :heavy_minus_sign: | N/A | | +| `id` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `integration_id` | *str* | :heavy_check_mark: | A Codat ID representing the integration. | fd321cb6-7963-4506-b873-e99593a45e30 | +| `integration_key` | *Optional[str]* | :heavy_minus_sign: | A unique four-character ID that identifies the platform of the company's data connection. This ensures continuity if the platform changes its name in the future. | | +| `last_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `link_url` | *str* | :heavy_check_mark: | The link URL your customers can use to authorize access to their business application. | https://link-api.codat.io/companies/86bd88cb-44ab-4dfb-b32f-87b19b14287f/connections/2e2eb431-c1fa-4dc9-93fa-d29781c12bcd/start | +| `platform_name` | *str* | :heavy_check_mark: | Name of integration connected to company. | | +| `source_id` | *str* | :heavy_check_mark: | A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`. | 35b92968-9851-4095-ad60-395c95cbcba4 | +| `source_type` | [shared.SourceType](../../models/shared/sourcetype.md) | :heavy_check_mark: | The type of platform of the connection. | Accounting | | `status` | [shared.DataConnectionStatus](../../models/shared/dataconnectionstatus.md) | :heavy_check_mark: | The current authorization status of the data connection. | | \ No newline at end of file diff --git a/platform/docs/models/shared/connectionmanagementaccesstoken.md b/platform/docs/models/shared/connectionmanagementaccesstoken.md index a6fa3b809..d2299f9cc 100644 --- a/platform/docs/models/shared/connectionmanagementaccesstoken.md +++ b/platform/docs/models/shared/connectionmanagementaccesstoken.md @@ -1,8 +1,8 @@ -# ConnectionManagementAccessToken - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +# ConnectionManagementAccessToken + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | `access_token` | *Optional[str]* | :heavy_minus_sign: | Access token that allows SMBs to manage connections that have access to their data. | eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c | \ No newline at end of file diff --git a/platform/docs/models/shared/connectionmanagementallowedorigins.md b/platform/docs/models/shared/connectionmanagementallowedorigins.md index b12d572bb..9bb286726 100644 --- a/platform/docs/models/shared/connectionmanagementallowedorigins.md +++ b/platform/docs/models/shared/connectionmanagementallowedorigins.md @@ -1,10 +1,8 @@ -# ConnectionManagementAllowedOrigins - -Success - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +# ConnectionManagementAllowedOrigins + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `allowed_origins` | List[*str*] | :heavy_minus_sign: | An array of allowed origins (i.e. your domains) to permit cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)).n resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)). | \ No newline at end of file diff --git a/platform/docs/models/shared/connections.md b/platform/docs/models/shared/connections.md index 69b3bdc2c..29a1b8ed3 100644 --- a/platform/docs/models/shared/connections.md +++ b/platform/docs/models/shared/connections.md @@ -1,12 +1,12 @@ -# Connections - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | -| `page_number` | *int* | :heavy_check_mark: | Current page number. | | -| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | -| `results` | List[[shared.Connection](../../models/shared/connection.md)] | :heavy_minus_sign: | N/A | | +# Connections + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | +| `page_number` | *int* | :heavy_check_mark: | Current page number. | | +| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | +| `results` | List[[shared.Connection](../../models/shared/connection.md)] | :heavy_minus_sign: | N/A | | | `total_results` | *int* | :heavy_check_mark: | Total number of items. | | \ No newline at end of file diff --git a/platform/docs/models/shared/connectionwebhook.md b/platform/docs/models/shared/connectionwebhook.md index 00894fb92..25a2abcaf 100644 --- a/platform/docs/models/shared/connectionwebhook.md +++ b/platform/docs/models/shared/connectionwebhook.md @@ -1,11 +1,11 @@ -# ConnectionWebhook - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | **Example 1:** connection.created
**Example 2:** connection.connected
**Example 3:** connection.disconnected
**Example 4:** connection.reconnected
**Example 5:** connection.deleted
**Example 6:** connection.failed | -| `generated_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the event. | ba29118f-5406-4e59-b05c-ba307ca38d01 | +# ConnectionWebhook + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | **Example 1:** connection.created
**Example 2:** connection.connected
**Example 3:** connection.disconnected
**Example 4:** connection.reconnected
**Example 5:** connection.deleted
**Example 6:** connection.failed | +| `generated_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the event. | ba29118f-5406-4e59-b05c-ba307ca38d01 | | `payload` | [Optional[shared.ConnectionWebhookPayload]](../../models/shared/connectionwebhookpayload.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/shared/connectionwebhookpayload.md b/platform/docs/models/shared/connectionwebhookpayload.md index 178010807..3b66568c8 100644 --- a/platform/docs/models/shared/connectionwebhookpayload.md +++ b/platform/docs/models/shared/connectionwebhookpayload.md @@ -1,9 +1,9 @@ -# ConnectionWebhookPayload - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `connection` | [Optional[shared.Connection]](../../models/shared/connection.md) | :heavy_minus_sign: | A connection represents a [company's](https://docs.codat.io/platform-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source.

A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to:

- [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection.
- [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections.
- [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections.
Any combination of accounting, banking, and commerce data connections is allowed.

Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). | {
"id": "ee2eb431-c0fa-4dc9-93fa-d29781c12bcd",
"integrationId": "bf083d72-62c7-493e-aec9-81b4dbba7e2c",
"integrationKey": "dfxm",
"sourceId": "bdd831ce-eebd-4896-89a7-20e5ee8989ee",
"platformName": "Basiq",
"linkUrl": "https://link-api.codat.io/companies/86bd88cb-44ab-4dfb-b32f-87b19b14287f/connections/ee2eb431-c0fa-4dc9-93fa-d29781c12bcd/start",
"status": "Linked",
"lastSync": "2022-10-27T10:22:43.6464237Z",
"created": "2022-10-27T09:53:29Z",
"sourceType": "Banking"
} | +# ConnectionWebhookPayload + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `connection` | [Optional[shared.Connection]](../../models/shared/connection.md) | :heavy_minus_sign: | A connection represents a [company's](https://docs.codat.io/platform-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source.

A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to:

- [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection.
- [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections.
- [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections.
Any combination of accounting, banking, and commerce data connections is allowed.

Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). | {
"id": "ee2eb431-c0fa-4dc9-93fa-d29781c12bcd",
"integrationId": "bf083d72-62c7-493e-aec9-81b4dbba7e2c",
"integrationKey": "dfxm",
"sourceId": "bdd831ce-eebd-4896-89a7-20e5ee8989ee",
"platformName": "Basiq",
"linkUrl": "https://link-api.codat.io/companies/86bd88cb-44ab-4dfb-b32f-87b19b14287f/connections/ee2eb431-c0fa-4dc9-93fa-d29781c12bcd/start",
"status": "Linked",
"lastSync": "2022-10-27T10:22:43.6464237Z",
"created": "2022-10-27T09:53:29Z",
"sourceType": "Banking"
} | | `reference_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/shared/content.md b/platform/docs/models/shared/content.md index 88bdbee7c..7f313d95e 100644 --- a/platform/docs/models/shared/content.md +++ b/platform/docs/models/shared/content.md @@ -1,7 +1,7 @@ -# Content - - -## Fields - -| Field | Type | Required | Description | +# Content + + +## Fields + +| Field | Type | Required | Description | | ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/platform/docs/models/shared/createapikey.md b/platform/docs/models/shared/createapikey.md index eec158de8..5bdc25b6b 100644 --- a/platform/docs/models/shared/createapikey.md +++ b/platform/docs/models/shared/createapikey.md @@ -1,10 +1,10 @@ -# CreateAPIKey - -Details about the newly created API key. - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------ | ------------------------------------------ | ------------------------------------------ | ------------------------------------------ | ------------------------------------------ | +# CreateAPIKey + +Details about the newly created API key. + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------ | ------------------------------------------ | ------------------------------------------ | ------------------------------------------ | ------------------------------------------ | | `name` | *OptionalNullable[str]* | :heavy_minus_sign: | A meaningful name assigned to the API key. | azure-invoice-finance-processor | \ No newline at end of file diff --git a/platform/docs/models/shared/createconnectionrequest.md b/platform/docs/models/shared/createconnectionrequest.md new file mode 100644 index 000000000..dcf930d2f --- /dev/null +++ b/platform/docs/models/shared/createconnectionrequest.md @@ -0,0 +1,8 @@ +# CreateConnectionRequest + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `platform_key` | *Optional[str]* | :heavy_minus_sign: | A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys. | \ No newline at end of file diff --git a/platform/docs/models/shared/currentstatus.md b/platform/docs/models/shared/currentstatus.md new file mode 100644 index 000000000..00681cb8e --- /dev/null +++ b/platform/docs/models/shared/currentstatus.md @@ -0,0 +1,36 @@ +# CurrentStatus + +## Example Usage + +```python +from codat_platform.models.shared import CurrentStatus + +value = CurrentStatus.INITIAL +``` + + +## Values + +| Name | Value | +| ---------------------- | ---------------------- | +| `INITIAL` | Initial | +| `QUEUED` | Queued | +| `FETCHING` | Fetching | +| `MAP_QUEUED` | MapQueued | +| `MAPPING` | Mapping | +| `COMPLETE` | Complete | +| `FETCH_ERROR` | FetchError | +| `MAP_ERROR` | MapError | +| `INTERNAL_ERROR` | InternalError | +| `PROCESSING_QUEUED` | ProcessingQueued | +| `PROCESSING` | Processing | +| `PROCESSING_ERROR` | ProcessingError | +| `VALIDATION_QUEUED` | ValidationQueued | +| `VALIDATING` | Validating | +| `VALIDATION_ERROR` | ValidationError | +| `AUTH_ERROR` | AuthError | +| `CANCELLED` | Cancelled | +| `NOT_SUPPORTED` | NotSupported | +| `RATE_LIMIT_ERROR` | RateLimitError | +| `PERMISSIONS_ERROR` | PermissionsError | +| `PREREQUISITE_NOT_MET` | PrerequisiteNotMet | \ No newline at end of file diff --git a/platform/docs/models/shared/customdatatypeconfiguration.md b/platform/docs/models/shared/customdatatypeconfiguration.md index 96059bd84..66d1ebdac 100644 --- a/platform/docs/models/shared/customdatatypeconfiguration.md +++ b/platform/docs/models/shared/customdatatypeconfiguration.md @@ -1,13 +1,13 @@ -# CustomDataTypeConfiguration - -Client's configuration details for a specific custom data type and platform pair. - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `data_source` | *Optional[str]* | :heavy_minus_sign: | Underlying endpoint of the source platform that will serve as a data source for the custom data type. This value is not validated by Codat. | -| `key_by` | List[*str*] | :heavy_minus_sign: | An array of properties from the source system that can be used to uniquely identify the records returned for the custom data type. This value is not validated by Codat. | -| `required_data` | Dict[str, *str*] | :heavy_minus_sign: | Properties required to be fetched from the underlying platform for the custom data type that is being configured. This value is not validated by Codat. | +# CustomDataTypeConfiguration + +Client's configuration details for a specific custom data type and platform pair. + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `data_source` | *Optional[str]* | :heavy_minus_sign: | Underlying endpoint of the source platform that will serve as a data source for the custom data type. This value is not validated by Codat. | +| `key_by` | List[*str*] | :heavy_minus_sign: | An array of properties from the source system that can be used to uniquely identify the records returned for the custom data type. This value is not validated by Codat. | +| `required_data` | Dict[str, *str*] | :heavy_minus_sign: | Properties required to be fetched from the underlying platform for the custom data type that is being configured. This value is not validated by Codat. | | `source_modified_date` | List[*str*] | :heavy_minus_sign: | Property in the source platform nominated by the client that defines the date when a record was last modified there. This value is not validated by Codat. | \ No newline at end of file diff --git a/platform/docs/models/shared/customdatatyperecord.md b/platform/docs/models/shared/customdatatyperecord.md index f546f29c9..3799d2774 100644 --- a/platform/docs/models/shared/customdatatyperecord.md +++ b/platform/docs/models/shared/customdatatyperecord.md @@ -1,10 +1,10 @@ -# CustomDataTypeRecord - - -## Fields - -| Field | Type | Required | Description | -| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| `content` | Dict[str, [shared.Content](../../models/shared/content.md)] | :heavy_minus_sign: | Values from the source system for the properties defined in the custom data type configuration. | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the record. | +# CustomDataTypeRecord + + +## Fields + +| Field | Type | Required | Description | +| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| `content` | Dict[str, [shared.Content](../../models/shared/content.md)] | :heavy_minus_sign: | Values from the source system for the properties defined in the custom data type configuration. | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the record. | | `modified_date` | [Optional[shared.ModifiedDate]](../../models/shared/modifieddate.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/customdatatyperecords.md b/platform/docs/models/shared/customdatatyperecords.md index f58835b8d..8cccf7c26 100644 --- a/platform/docs/models/shared/customdatatyperecords.md +++ b/platform/docs/models/shared/customdatatyperecords.md @@ -1,13 +1,13 @@ -# CustomDataTypeRecords - -Resulting records pulled from the source platform for a specific custom data type. - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -| `page_number` | *Optional[int]* | :heavy_minus_sign: | Current page number. | -| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of items to return in results array. | -| `results` | List[[shared.CustomDataTypeRecord](../../models/shared/customdatatyperecord.md)] | :heavy_minus_sign: | N/A | +# CustomDataTypeRecords + +Resulting records pulled from the source platform for a specific custom data type. + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `page_number` | *Optional[int]* | :heavy_minus_sign: | Current page number. | +| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of items to return in results array. | +| `results` | List[[shared.CustomDataTypeRecord](../../models/shared/customdatatyperecord.md)] | :heavy_minus_sign: | N/A | | `total_results` | *Optional[int]* | :heavy_minus_sign: | Total number of items. | \ No newline at end of file diff --git a/platform/docs/models/shared/dataconnectionerror.md b/platform/docs/models/shared/dataconnectionerror.md index 33b523477..96b4828fa 100644 --- a/platform/docs/models/shared/dataconnectionerror.md +++ b/platform/docs/models/shared/dataconnectionerror.md @@ -1,13 +1,13 @@ -# DataConnectionError - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `error_message` | *Optional[str]* | :heavy_minus_sign: | A message about a error returned by Codat. | | -| `errored_on_utc` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `resolved_on_utc` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `status` | [OptionalNullable[shared.ErrorStatus]](../../models/shared/errorstatus.md) | :heavy_minus_sign: | The current status of a transient error. Null statuses indicate that the error is not transient. | | -| `status_code` | *Optional[str]* | :heavy_minus_sign: | The HTTP status code returned by the source platform when the error occurred. | | +# DataConnectionError + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `error_message` | *Optional[str]* | :heavy_minus_sign: | A message about a error returned by Codat. | | +| `errored_on_utc` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `resolved_on_utc` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `status` | [OptionalNullable[shared.ErrorStatus]](../../models/shared/errorstatus.md) | :heavy_minus_sign: | The current status of a transient error. Null statuses indicate that the error is not transient. | | +| `status_code` | *Optional[str]* | :heavy_minus_sign: | The HTTP status code returned by the source platform when the error occurred. | | | `status_text` | *Optional[str]* | :heavy_minus_sign: | A non-numeric status code/text returned by the source platform when the error occurred. | | \ No newline at end of file diff --git a/platform/docs/models/shared/dataconnectionstatus.md b/platform/docs/models/shared/dataconnectionstatus.md index 9221c42f8..3889583c1 100644 --- a/platform/docs/models/shared/dataconnectionstatus.md +++ b/platform/docs/models/shared/dataconnectionstatus.md @@ -1,21 +1,21 @@ -# DataConnectionStatus - -The current authorization status of the data connection. - -## Example Usage - -```python -from codat_platform.models.shared import DataConnectionStatus - -value = DataConnectionStatus.PENDING_AUTH -``` - - -## Values - -| Name | Value | -| -------------- | -------------- | -| `PENDING_AUTH` | PendingAuth | -| `LINKED` | Linked | -| `UNLINKED` | Unlinked | +# DataConnectionStatus + +The current authorization status of the data connection. + +## Example Usage + +```python +from codat_platform.models.shared import DataConnectionStatus + +value = DataConnectionStatus.PENDING_AUTH +``` + + +## Values + +| Name | Value | +| -------------- | -------------- | +| `PENDING_AUTH` | PendingAuth | +| `LINKED` | Linked | +| `UNLINKED` | Unlinked | | `DEAUTHORIZED` | Deauthorized | \ No newline at end of file diff --git a/platform/docs/models/shared/datasetstatus.md b/platform/docs/models/shared/datasetstatus.md index 3ae512f26..a48827676 100644 --- a/platform/docs/models/shared/datasetstatus.md +++ b/platform/docs/models/shared/datasetstatus.md @@ -1,38 +1,38 @@ -# DatasetStatus - -The current status of the dataset. - -## Example Usage - -```python -from codat_platform.models.shared import DatasetStatus - -value = DatasetStatus.INITIAL -``` - - -## Values - -| Name | Value | -| ---------------------- | ---------------------- | -| `INITIAL` | Initial | -| `QUEUED` | Queued | -| `FETCHING` | Fetching | -| `MAP_QUEUED` | MapQueued | -| `MAPPING` | Mapping | -| `COMPLETE` | Complete | -| `FETCH_ERROR` | FetchError | -| `MAP_ERROR` | MapError | -| `INTERNAL_ERROR` | InternalError | -| `PROCESSING_QUEUED` | ProcessingQueued | -| `PROCESSING` | Processing | -| `PROCESSING_ERROR` | ProcessingError | -| `VALIDATION_QUEUED` | ValidationQueued | -| `VALIDATING` | Validating | -| `VALIDATION_ERROR` | ValidationError | -| `AUTH_ERROR` | AuthError | -| `CANCELLED` | Cancelled | -| `NOT_SUPPORTED` | NotSupported | -| `RATE_LIMIT_ERROR` | RateLimitError | -| `PERMISSIONS_ERROR` | PermissionsError | +# DatasetStatus + +The current status of the dataset. + +## Example Usage + +```python +from codat_platform.models.shared import DatasetStatus + +value = DatasetStatus.INITIAL +``` + + +## Values + +| Name | Value | +| ---------------------- | ---------------------- | +| `INITIAL` | Initial | +| `QUEUED` | Queued | +| `FETCHING` | Fetching | +| `MAP_QUEUED` | MapQueued | +| `MAPPING` | Mapping | +| `COMPLETE` | Complete | +| `FETCH_ERROR` | FetchError | +| `MAP_ERROR` | MapError | +| `INTERNAL_ERROR` | InternalError | +| `PROCESSING_QUEUED` | ProcessingQueued | +| `PROCESSING` | Processing | +| `PROCESSING_ERROR` | ProcessingError | +| `VALIDATION_QUEUED` | ValidationQueued | +| `VALIDATING` | Validating | +| `VALIDATION_ERROR` | ValidationError | +| `AUTH_ERROR` | AuthError | +| `CANCELLED` | Cancelled | +| `NOT_SUPPORTED` | NotSupported | +| `RATE_LIMIT_ERROR` | RateLimitError | +| `PERMISSIONS_ERROR` | PermissionsError | | `PREREQUISITE_NOT_MET` | PrerequisiteNotMet | \ No newline at end of file diff --git a/platform/docs/models/shared/datastatus.md b/platform/docs/models/shared/datastatus.md index c89b47244..d5b8102bb 100644 --- a/platform/docs/models/shared/datastatus.md +++ b/platform/docs/models/shared/datastatus.md @@ -1,14 +1,14 @@ -# DataStatus - -Describes the state of data in the Codat cache for a company and data type - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `current_status` | [shared.Status](../../models/shared/status.md) | :heavy_check_mark: | The current status of the dataset. | | -| `data_type` | [shared.DataTypes](../../models/shared/datatypes.md) | :heavy_check_mark: | Available data types | invoices | -| `last_successful_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `latest_successful_sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the most recent successful sync of data type. | 8220fc90-55b6-47bc-9417-48ac6ea93101 | +# DataStatus + +Describes the state of data in the Codat cache for a company and data type + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `current_status` | [shared.Status](../../models/shared/status.md) | :heavy_check_mark: | The current status of the dataset. | | +| `data_type` | [shared.DataTypes](../../models/shared/datatypes.md) | :heavy_check_mark: | Available data types | invoices | +| `last_successful_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `latest_successful_sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the most recent successful sync of data type. | 8220fc90-55b6-47bc-9417-48ac6ea93101 | | `latest_sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for most recent sync of data type. | ad474a37-2003-478e-baee-9af9f1ec2fe3 | \ No newline at end of file diff --git a/platform/docs/models/shared/datastatuses.md b/platform/docs/models/shared/datastatuses.md index 935457bb3..18e87e160 100644 --- a/platform/docs/models/shared/datastatuses.md +++ b/platform/docs/models/shared/datastatuses.md @@ -1,50 +1,50 @@ -# DataStatuses - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `account_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `balance_sheet` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `bank_accounts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `bank_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `banking_account_balances` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `banking_accounts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `banking_transaction_categories` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `banking_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `bill_credit_notes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `bill_payments` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `bills` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `cash_flow_statement` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `chart_of_accounts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_company_info` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_customers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_disputes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_locations` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_orders` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_payment_methods` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_payments` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_product_categories` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_products` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_tax_components` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `company` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `credit_notes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `customers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `direct_costs` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `direct_incomes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `invoices` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `item_receipts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `items` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `journal_entries` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `journals` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `payment_methods` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `payments` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `profit_and_loss` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `purchase_orders` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `sales_orders` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `suppliers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `tax_rates` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `tracking_categories` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +# DataStatuses + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `account_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `balance_sheet` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `bank_accounts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `bank_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `banking_account_balances` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `banking_accounts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `banking_transaction_categories` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `banking_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `bill_credit_notes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `bill_payments` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `bills` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `cash_flow_statement` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `chart_of_accounts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `commerce_company_info` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `commerce_customers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `commerce_disputes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `commerce_locations` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `commerce_orders` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `commerce_payment_methods` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `commerce_payments` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `commerce_product_categories` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `commerce_products` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `commerce_tax_components` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `commerce_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `company` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `credit_notes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `customers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `direct_costs` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `direct_incomes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `invoices` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `item_receipts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `items` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `journal_entries` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `journals` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `payment_methods` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `payments` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `profit_and_loss` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `purchase_orders` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `sales_orders` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `suppliers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `tax_rates` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | +| `tracking_categories` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | | `transfers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | \ No newline at end of file diff --git a/platform/docs/models/shared/datatype.md b/platform/docs/models/shared/datatype.md index 3352460d2..3d1c99473 100644 --- a/platform/docs/models/shared/datatype.md +++ b/platform/docs/models/shared/datatype.md @@ -1,60 +1,75 @@ -# DataType - -Available data types - -## Example Usage - -```python -from codat_platform.models.shared import DataType - -value = DataType.ACCOUNT_TRANSACTIONS -``` - - -## Values - -| Name | Value | -| -------------------------------- | -------------------------------- | -| `ACCOUNT_TRANSACTIONS` | accountTransactions | -| `BALANCE_SHEET` | balanceSheet | -| `BANK_ACCOUNTS` | bankAccounts | -| `BANK_TRANSACTIONS` | bankTransactions | -| `BILL_CREDIT_NOTES` | billCreditNotes | -| `BILL_PAYMENTS` | billPayments | -| `BILLS` | bills | -| `CASH_FLOW_STATEMENT` | cashFlowStatement | -| `CHART_OF_ACCOUNTS` | chartOfAccounts | -| `COMPANY` | company | -| `CREDIT_NOTES` | creditNotes | -| `CUSTOMERS` | customers | -| `DIRECT_COSTS` | directCosts | -| `DIRECT_INCOMES` | directIncomes | -| `INVOICES` | invoices | -| `ITEM_RECEIPTS` | itemReceipts | -| `ITEMS` | items | -| `JOURNAL_ENTRIES` | journalEntries | -| `JOURNALS` | journals | -| `PAYMENT_METHODS` | paymentMethods | -| `PAYMENTS` | payments | -| `PROFIT_AND_LOSS` | profitAndLoss | -| `PURCHASE_ORDERS` | purchaseOrders | -| `SALES_ORDERS` | salesOrders | -| `SUPPLIERS` | suppliers | -| `TAX_RATES` | taxRates | -| `TRACKING_CATEGORIES` | trackingCategories | -| `TRANSFERS` | transfers | -| `BANKING_ACCOUNT_BALANCES` | banking-accountBalances | -| `BANKING_ACCOUNTS` | banking-accounts | -| `BANKING_TRANSACTION_CATEGORIES` | banking-transactionCategories | -| `BANKING_TRANSACTIONS` | banking-transactions | -| `COMMERCE_COMPANY_INFO` | commerce-companyInfo | -| `COMMERCE_CUSTOMERS` | commerce-customers | -| `COMMERCE_DISPUTES` | commerce-disputes | -| `COMMERCE_LOCATIONS` | commerce-locations | -| `COMMERCE_ORDERS` | commerce-orders | -| `COMMERCE_PAYMENT_METHODS` | commerce-paymentMethods | -| `COMMERCE_PAYMENTS` | commerce-payments | -| `COMMERCE_PRODUCT_CATEGORIES` | commerce-productCategories | -| `COMMERCE_PRODUCTS` | commerce-products | -| `COMMERCE_TAX_COMPONENTS` | commerce-taxComponents | -| `COMMERCE_TRANSACTIONS` | commerce-transactions | \ No newline at end of file +# DataType + +Available data types + +## Example Usage + +```python +from codat_platform.models.shared import DataType + +value = DataType.ACCOUNT_TRANSACTIONS +``` + + +## Values + +| Name | Value | +| -------------------------------------- | -------------------------------------- | +| `ACCOUNT_TRANSACTIONS` | accountTransactions | +| `BALANCE_SHEET` | balanceSheet | +| `BANK_ACCOUNTS` | bankAccounts | +| `BANK_TRANSACTIONS` | bankTransactions | +| `BILL_CREDIT_NOTES` | billCreditNotes | +| `BILL_PAYMENTS` | billPayments | +| `BILLS` | bills | +| `CASH_FLOW_STATEMENT` | cashFlowStatement | +| `CHART_OF_ACCOUNTS` | chartOfAccounts | +| `COMPANY` | company | +| `CREDIT_NOTES` | creditNotes | +| `CUSTOMERS` | customers | +| `DIRECT_COSTS` | directCosts | +| `DIRECT_INCOMES` | directIncomes | +| `INVOICES` | invoices | +| `ITEM_RECEIPTS` | itemReceipts | +| `ITEMS` | items | +| `JOURNAL_ENTRIES` | journalEntries | +| `JOURNALS` | journals | +| `PAYMENT_METHODS` | paymentMethods | +| `PAYMENTS` | payments | +| `PROFIT_AND_LOSS` | profitAndLoss | +| `PURCHASE_ORDERS` | purchaseOrders | +| `SALES_ORDERS` | salesOrders | +| `SUPPLIERS` | suppliers | +| `TAX_RATES` | taxRates | +| `TRACKING_CATEGORIES` | trackingCategories | +| `TRANSFERS` | transfers | +| `BANKING_MINUS_ACCOUNT_BALANCES` | banking-accountBalances | +| `BANKING_ACCOUNT_BALANCES` | banking-accountBalances | +| `BANKING_MINUS_ACCOUNTS` | banking-accounts | +| `BANKING_ACCOUNTS` | banking-accounts | +| `BANKING_MINUS_TRANSACTION_CATEGORIES` | banking-transactionCategories | +| `BANKING_TRANSACTION_CATEGORIES` | banking-transactionCategories | +| `BANKING_MINUS_TRANSACTIONS` | banking-transactions | +| `BANKING_TRANSACTIONS` | banking-transactions | +| `COMMERCE_MINUS_COMPANY_INFO` | commerce-companyInfo | +| `COMMERCE_COMPANY_INFO` | commerce-companyInfo | +| `COMMERCE_MINUS_CUSTOMERS` | commerce-customers | +| `COMMERCE_CUSTOMERS` | commerce-customers | +| `COMMERCE_MINUS_DISPUTES` | commerce-disputes | +| `COMMERCE_DISPUTES` | commerce-disputes | +| `COMMERCE_MINUS_LOCATIONS` | commerce-locations | +| `COMMERCE_LOCATIONS` | commerce-locations | +| `COMMERCE_MINUS_ORDERS` | commerce-orders | +| `COMMERCE_ORDERS` | commerce-orders | +| `COMMERCE_MINUS_PAYMENT_METHODS` | commerce-paymentMethods | +| `COMMERCE_PAYMENT_METHODS` | commerce-paymentMethods | +| `COMMERCE_MINUS_PAYMENTS` | commerce-payments | +| `COMMERCE_PAYMENTS` | commerce-payments | +| `COMMERCE_MINUS_PRODUCT_CATEGORIES` | commerce-productCategories | +| `COMMERCE_PRODUCT_CATEGORIES` | commerce-productCategories | +| `COMMERCE_MINUS_PRODUCTS` | commerce-products | +| `COMMERCE_PRODUCTS` | commerce-products | +| `COMMERCE_MINUS_TAX_COMPONENTS` | commerce-taxComponents | +| `COMMERCE_TAX_COMPONENTS` | commerce-taxComponents | +| `COMMERCE_MINUS_TRANSACTIONS` | commerce-transactions | +| `COMMERCE_TRANSACTIONS` | commerce-transactions | \ No newline at end of file diff --git a/platform/docs/models/shared/datatypefeature.md b/platform/docs/models/shared/datatypefeature.md index 1698aed98..68998724b 100644 --- a/platform/docs/models/shared/datatypefeature.md +++ b/platform/docs/models/shared/datatypefeature.md @@ -1,11 +1,11 @@ -# DataTypeFeature - -Describes support for a given datatype and associated operations - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | -| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | +# DataTypeFeature + +Describes support for a given datatype and associated operations + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | | `supported_features` | List[[shared.SupportedFeature](../../models/shared/supportedfeature.md)] | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/shared/datatypereadsummary.md b/platform/docs/models/shared/datatypereadsummary.md index 57d2cf76c..e3a4c18d6 100644 --- a/platform/docs/models/shared/datatypereadsummary.md +++ b/platform/docs/models/shared/datatypereadsummary.md @@ -1,12 +1,12 @@ -# DataTypeReadSummary - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | -| `connection_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | -| `issues` | List[[shared.Issue](../../models/shared/issue.md)] | :heavy_minus_sign: | A array of issues encountered during a data read. | | -| `records_modified` | *Optional[bool]* | :heavy_minus_sign: | `True` if records have been created, updated or deleted in Codat's cache. | false | -| `status` | [Optional[shared.Status]](../../models/shared/status.md) | :heavy_minus_sign: | The current status of the dataset. | | \ No newline at end of file +# DataTypeReadSummary + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| `connection_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for a company's data connection. | +| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | +| `issues` | List[[shared.Issue](../../models/shared/issue.md)] | :heavy_minus_sign: | A array of issues encountered during a data read. | +| `records_modified` | *Optional[bool]* | :heavy_minus_sign: | `True` if records have been created, updated or deleted in Codat's cache. | +| `status` | [Optional[shared.Status]](../../models/shared/status.md) | :heavy_minus_sign: | The current status of the dataset. | \ No newline at end of file diff --git a/platform/docs/models/shared/datatypes.md b/platform/docs/models/shared/datatypes.md index 2d59617ca..fae16a063 100644 --- a/platform/docs/models/shared/datatypes.md +++ b/platform/docs/models/shared/datatypes.md @@ -1,60 +1,60 @@ -# DataTypes - -Available data types - -## Example Usage - -```python -from codat_platform.models.shared import DataTypes - -value = DataTypes.ACCOUNT_TRANSACTIONS -``` - - -## Values - -| Name | Value | -| -------------------------------- | -------------------------------- | -| `ACCOUNT_TRANSACTIONS` | accountTransactions | -| `BALANCE_SHEET` | balanceSheet | -| `BANK_ACCOUNTS` | bankAccounts | -| `BANK_TRANSACTIONS` | bankTransactions | -| `BILL_CREDIT_NOTES` | billCreditNotes | -| `BILL_PAYMENTS` | billPayments | -| `BILLS` | bills | -| `CASH_FLOW_STATEMENT` | cashFlowStatement | -| `CHART_OF_ACCOUNTS` | chartOfAccounts | -| `COMPANY` | company | -| `CREDIT_NOTES` | creditNotes | -| `CUSTOMERS` | customers | -| `DIRECT_COSTS` | directCosts | -| `DIRECT_INCOMES` | directIncomes | -| `INVOICES` | invoices | -| `ITEM_RECEIPTS` | itemReceipts | -| `ITEMS` | items | -| `JOURNAL_ENTRIES` | journalEntries | -| `JOURNALS` | journals | -| `PAYMENT_METHODS` | paymentMethods | -| `PAYMENTS` | payments | -| `PROFIT_AND_LOSS` | profitAndLoss | -| `PURCHASE_ORDERS` | purchaseOrders | -| `SALES_ORDERS` | salesOrders | -| `SUPPLIERS` | suppliers | -| `TAX_RATES` | taxRates | -| `TRACKING_CATEGORIES` | trackingCategories | -| `TRANSFERS` | transfers | -| `BANKING_ACCOUNT_BALANCES` | banking-accountBalances | -| `BANKING_ACCOUNTS` | banking-accounts | -| `BANKING_TRANSACTION_CATEGORIES` | banking-transactionCategories | -| `BANKING_TRANSACTIONS` | banking-transactions | -| `COMMERCE_COMPANY_INFO` | commerce-companyInfo | -| `COMMERCE_CUSTOMERS` | commerce-customers | -| `COMMERCE_DISPUTES` | commerce-disputes | -| `COMMERCE_LOCATIONS` | commerce-locations | -| `COMMERCE_ORDERS` | commerce-orders | -| `COMMERCE_PAYMENT_METHODS` | commerce-paymentMethods | -| `COMMERCE_PAYMENTS` | commerce-payments | -| `COMMERCE_PRODUCT_CATEGORIES` | commerce-productCategories | -| `COMMERCE_PRODUCTS` | commerce-products | -| `COMMERCE_TAX_COMPONENTS` | commerce-taxComponents | +# DataTypes + +Available data types + +## Example Usage + +```python +from codat_platform.models.shared import DataTypes + +value = DataTypes.ACCOUNT_TRANSACTIONS +``` + + +## Values + +| Name | Value | +| -------------------------------- | -------------------------------- | +| `ACCOUNT_TRANSACTIONS` | accountTransactions | +| `BALANCE_SHEET` | balanceSheet | +| `BANK_ACCOUNTS` | bankAccounts | +| `BANK_TRANSACTIONS` | bankTransactions | +| `BILL_CREDIT_NOTES` | billCreditNotes | +| `BILL_PAYMENTS` | billPayments | +| `BILLS` | bills | +| `CASH_FLOW_STATEMENT` | cashFlowStatement | +| `CHART_OF_ACCOUNTS` | chartOfAccounts | +| `COMPANY` | company | +| `CREDIT_NOTES` | creditNotes | +| `CUSTOMERS` | customers | +| `DIRECT_COSTS` | directCosts | +| `DIRECT_INCOMES` | directIncomes | +| `INVOICES` | invoices | +| `ITEM_RECEIPTS` | itemReceipts | +| `ITEMS` | items | +| `JOURNAL_ENTRIES` | journalEntries | +| `JOURNALS` | journals | +| `PAYMENT_METHODS` | paymentMethods | +| `PAYMENTS` | payments | +| `PROFIT_AND_LOSS` | profitAndLoss | +| `PURCHASE_ORDERS` | purchaseOrders | +| `SALES_ORDERS` | salesOrders | +| `SUPPLIERS` | suppliers | +| `TAX_RATES` | taxRates | +| `TRACKING_CATEGORIES` | trackingCategories | +| `TRANSFERS` | transfers | +| `BANKING_ACCOUNT_BALANCES` | banking-accountBalances | +| `BANKING_ACCOUNTS` | banking-accounts | +| `BANKING_TRANSACTION_CATEGORIES` | banking-transactionCategories | +| `BANKING_TRANSACTIONS` | banking-transactions | +| `COMMERCE_COMPANY_INFO` | commerce-companyInfo | +| `COMMERCE_CUSTOMERS` | commerce-customers | +| `COMMERCE_DISPUTES` | commerce-disputes | +| `COMMERCE_LOCATIONS` | commerce-locations | +| `COMMERCE_ORDERS` | commerce-orders | +| `COMMERCE_PAYMENT_METHODS` | commerce-paymentMethods | +| `COMMERCE_PAYMENTS` | commerce-payments | +| `COMMERCE_PRODUCT_CATEGORIES` | commerce-productCategories | +| `COMMERCE_PRODUCTS` | commerce-products | +| `COMMERCE_TAX_COMPONENTS` | commerce-taxComponents | | `COMMERCE_TRANSACTIONS` | commerce-transactions | \ No newline at end of file diff --git a/platform/docs/models/shared/datatypewritewebhook.md b/platform/docs/models/shared/datatypewritewebhook.md index 0b0e4f102..d98449786 100644 --- a/platform/docs/models/shared/datatypewritewebhook.md +++ b/platform/docs/models/shared/datatypewritewebhook.md @@ -1,11 +1,11 @@ -# DataTypeWriteWebhook - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | **Example 1:** bills.write.successful
**Example 2:** bills.write.unsuccessful | -| `generated_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the event. | ba29118f-5406-4e59-b05c-ba307ca38d01 | +# DataTypeWriteWebhook + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | **Example 1:** bills.write.successful
**Example 2:** bills.write.unsuccessful | +| `generated_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the event. | ba29118f-5406-4e59-b05c-ba307ca38d01 | | `payload` | [Optional[shared.DataTypeWriteWebhookPayload]](../../models/shared/datatypewritewebhookpayload.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/shared/datatypewritewebhookpayload.md b/platform/docs/models/shared/datatypewritewebhookpayload.md index 5d08afbf5..3c7e1f9c1 100644 --- a/platform/docs/models/shared/datatypewritewebhookpayload.md +++ b/platform/docs/models/shared/datatypewritewebhookpayload.md @@ -1,16 +1,16 @@ -# DataTypeWriteWebhookPayload - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `attachment_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier for the uploaded attachment, null if no attachment uploaded. | | -| `completed_on_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `connection_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the write request. This is also known as the push operation ID. | | -| `record` | [Optional[shared.DataTypeWriteWebhookRecord]](../../models/shared/datatypewritewebhookrecord.md) | :heavy_minus_sign: | N/A | | -| `reference_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | N/A | | -| `requested_on_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `status` | [Optional[shared.WriteStatus]](../../models/shared/writestatus.md) | :heavy_minus_sign: | The current status of the write request, which is the same as the push operation status. | | -| `type` | [Optional[shared.WriteType]](../../models/shared/writetype.md) | :heavy_minus_sign: | Type of write request. | | \ No newline at end of file +# DataTypeWriteWebhookPayload + + +## Fields + +| Field | Type | Required | Description | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `attachment_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier for the uploaded attachment, null if no attachment uploaded. | +| `completed_on_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | +| `connection_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for a company's data connection. | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the write request. This is also known as the push operation ID. | +| `record` | [Optional[shared.DataTypeWriteWebhookRecord]](../../models/shared/datatypewritewebhookrecord.md) | :heavy_minus_sign: | N/A | +| `reference_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | N/A | +| `requested_on_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | +| `status` | [Optional[shared.WriteStatus]](../../models/shared/writestatus.md) | :heavy_minus_sign: | N/A | +| `type` | [Optional[shared.WriteType]](../../models/shared/writetype.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/datatypewritewebhookrecord.md b/platform/docs/models/shared/datatypewritewebhookrecord.md index 1f6adc677..881bcda72 100644 --- a/platform/docs/models/shared/datatypewritewebhookrecord.md +++ b/platform/docs/models/shared/datatypewritewebhookrecord.md @@ -1,8 +1,8 @@ -# DataTypeWriteWebhookRecord - - -## Fields - -| Field | Type | Required | Description | -| --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | +# DataTypeWriteWebhookRecord + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `id` | *Optional[str]* | :heavy_minus_sign: | The unique identifier of the data type created, updated, deleted, or had an attachment uploaded in the accounting platform. | \ No newline at end of file diff --git a/platform/docs/models/shared/errormessage.md b/platform/docs/models/shared/errormessage.md index 4b5d4654a..eeefa0c01 100644 --- a/platform/docs/models/shared/errormessage.md +++ b/platform/docs/models/shared/errormessage.md @@ -1,16 +1,14 @@ -# ErrorMessage - -Too many requests were made in a given amount of time. Wait a short period and then try again. - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `can_be_retried` | *Optional[str]* | :heavy_minus_sign: | `True` if the error occurred transiently and can be retried. | -| `correlation_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier used to propagate to all downstream services and determine the source of the error. | -| `detailed_error_code` | *Optional[int]* | :heavy_minus_sign: | Machine readable error code used to automate processes based on the code returned. | -| `error` | *Optional[str]* | :heavy_minus_sign: | A brief description of the error. | -| `service` | *Optional[str]* | :heavy_minus_sign: | Codat's service the returned the error. | -| `status_code` | *Optional[int]* | :heavy_minus_sign: | The HTTP status code returned by the error. | +# ErrorMessage + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `can_be_retried` | *Optional[str]* | :heavy_minus_sign: | `True` if the error occurred transiently and can be retried. | +| `correlation_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier used to propagate to all downstream services and determine the source of the error. | +| `detailed_error_code` | *Optional[int]* | :heavy_minus_sign: | Machine readable error code used to automate processes based on the code returned. | +| `error` | *Optional[str]* | :heavy_minus_sign: | A brief description of the error. | +| `service` | *Optional[str]* | :heavy_minus_sign: | Codat's service the returned the error. | +| `status_code` | *Optional[int]* | :heavy_minus_sign: | The HTTP status code returned by the error. | | `validation` | [OptionalNullable[shared.ErrorValidation]](../../models/shared/errorvalidation.md) | :heavy_minus_sign: | A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here. | \ No newline at end of file diff --git a/platform/docs/models/shared/errorstatus.md b/platform/docs/models/shared/errorstatus.md index aeb1f5dbd..b788bc4eb 100644 --- a/platform/docs/models/shared/errorstatus.md +++ b/platform/docs/models/shared/errorstatus.md @@ -1,19 +1,19 @@ -# ErrorStatus - -The current status of a transient error. Null statuses indicate that the error is not transient. - -## Example Usage - -```python -from codat_platform.models.shared import ErrorStatus - -value = ErrorStatus.ACTIVE -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `ACTIVE` | Active | +# ErrorStatus + +The current status of a transient error. Null statuses indicate that the error is not transient. + +## Example Usage + +```python +from codat_platform.models.shared import ErrorStatus + +value = ErrorStatus.ACTIVE +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `ACTIVE` | Active | | `RESOLVED` | Resolved | \ No newline at end of file diff --git a/platform/docs/models/shared/errorvalidation.md b/platform/docs/models/shared/errorvalidation.md index 122badd9d..618d40ff2 100644 --- a/platform/docs/models/shared/errorvalidation.md +++ b/platform/docs/models/shared/errorvalidation.md @@ -1,11 +1,9 @@ -# ErrorValidation - -A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here. - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | -| `errors` | List[[shared.ErrorValidationItem](../../models/shared/errorvalidationitem.md)] | :heavy_minus_sign: | N/A | +# ErrorValidation + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `errors` | List[[shared.ErrorValidationItem](../../models/shared/errorvalidationitem.md)] | :heavy_minus_sign: | N/A | | `warnings` | List[[shared.ErrorValidationItem](../../models/shared/errorvalidationitem.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/errorvalidationitem.md b/platform/docs/models/shared/errorvalidationitem.md index fca2ef14a..a2ea37332 100644 --- a/platform/docs/models/shared/errorvalidationitem.md +++ b/platform/docs/models/shared/errorvalidationitem.md @@ -1,10 +1,10 @@ -# ErrorValidationItem - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -| `item_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier for a validation item. | -| `message` | *OptionalNullable[str]* | :heavy_minus_sign: | A message outlining validation item's issue. | +# ErrorValidationItem + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | +| `item_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier for a validation item. | +| `message` | *OptionalNullable[str]* | :heavy_minus_sign: | A message outlining validation item's issue. | | `validator_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of validator. | \ No newline at end of file diff --git a/platform/docs/models/shared/featurestate.md b/platform/docs/models/shared/featurestate.md index effbd1bab..dce6ca422 100644 --- a/platform/docs/models/shared/featurestate.md +++ b/platform/docs/models/shared/featurestate.md @@ -1,23 +1,23 @@ -# FeatureState - -The current release state of the feature. - -## Example Usage - -```python -from codat_platform.models.shared import FeatureState - -value = FeatureState.RELEASE -``` - - -## Values - -| Name | Value | -| ----------------- | ----------------- | -| `RELEASE` | Release | -| `ALPHA` | Alpha | -| `BETA` | Beta | -| `DEPRECATED` | Deprecated | -| `NOT_SUPPORTED` | NotSupported | +# FeatureState + +The current release state of the feature. + +## Example Usage + +```python +from codat_platform.models.shared import FeatureState + +value = FeatureState.RELEASE +``` + + +## Values + +| Name | Value | +| ----------------- | ----------------- | +| `RELEASE` | Release | +| `ALPHA` | Alpha | +| `BETA` | Beta | +| `DEPRECATED` | Deprecated | +| `NOT_SUPPORTED` | NotSupported | | `NOT_IMPLEMENTED` | NotImplemented | \ No newline at end of file diff --git a/platform/docs/models/shared/featuretype.md b/platform/docs/models/shared/featuretype.md index 165da727d..4cb04e90a 100644 --- a/platform/docs/models/shared/featuretype.md +++ b/platform/docs/models/shared/featuretype.md @@ -1,27 +1,25 @@ -# FeatureType - -The type of feature. - -## Example Usage - -```python -from codat_platform.models.shared import FeatureType - -value = FeatureType.GET -``` - - -## Values - -| Name | Value | -| --------------------- | --------------------- | -| `GET` | Get | -| `POST` | Post | -| `CATEGORIZATION` | Categorization | -| `DELETE` | Delete | -| `PUT` | Put | -| `GET_AS_PDF` | GetAsPdf | -| `DOWNLOAD_ATTACHMENT` | DownloadAttachment | -| `GET_ATTACHMENT` | GetAttachment | -| `GET_ATTACHMENTS` | GetAttachments | +# FeatureType + +## Example Usage + +```python +from codat_platform.models.shared import FeatureType + +value = FeatureType.GET +``` + + +## Values + +| Name | Value | +| --------------------- | --------------------- | +| `GET` | Get | +| `POST` | Post | +| `CATEGORIZATION` | Categorization | +| `DELETE` | Delete | +| `PUT` | Put | +| `GET_AS_PDF` | GetAsPdf | +| `DOWNLOAD_ATTACHMENT` | DownloadAttachment | +| `GET_ATTACHMENT` | GetAttachment | +| `GET_ATTACHMENTS` | GetAttachments | | `UPLOAD_ATTACHMENT` | UploadAttachment | \ No newline at end of file diff --git a/platform/docs/models/shared/halref.md b/platform/docs/models/shared/halref.md index 94c6476ff..75aa86923 100644 --- a/platform/docs/models/shared/halref.md +++ b/platform/docs/models/shared/halref.md @@ -1,8 +1,8 @@ -# HalRef - - -## Fields - -| Field | Type | Required | Description | -| ------------------------ | ------------------------ | ------------------------ | ------------------------ | +# HalRef + + +## Fields + +| Field | Type | Required | Description | +| ------------------------ | ------------------------ | ------------------------ | ------------------------ | | `href` | *Optional[str]* | :heavy_minus_sign: | Uri hypertext reference. | \ No newline at end of file diff --git a/platform/docs/models/shared/imagereference.md b/platform/docs/models/shared/imagereference.md index 1247f6a83..07999ddbe 100644 --- a/platform/docs/models/shared/imagereference.md +++ b/platform/docs/models/shared/imagereference.md @@ -1,11 +1,11 @@ -# ImageReference - -Image reference. - - -## Fields - -| Field | Type | Required | Description | -| --------------------------------------------- | --------------------------------------------- | --------------------------------------------- | --------------------------------------------- | -| `alt` | *Optional[str]* | :heavy_minus_sign: | Alternative text when image is not available. | +# ImageReference + +Image reference. + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------- | --------------------------------------------- | --------------------------------------------- | --------------------------------------------- | +| `alt` | *Optional[str]* | :heavy_minus_sign: | Alternative text when image is not available. | | `src` | *Optional[str]* | :heavy_minus_sign: | Source URL for image. | \ No newline at end of file diff --git a/platform/docs/models/shared/integration.md b/platform/docs/models/shared/integration.md index 7bd072311..3dd066ed9 100644 --- a/platform/docs/models/shared/integration.md +++ b/platform/docs/models/shared/integration.md @@ -1,20 +1,20 @@ -# Integration - -An integration that Codat supports - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `data_provided_by` | *Optional[str]* | :heavy_minus_sign: | The name of the data provider. | | -| `datatype_features` | List[[shared.DataTypeFeature](../../models/shared/datatypefeature.md)] | :heavy_minus_sign: | N/A | | -| `enabled` | *bool* | :heavy_check_mark: | Whether this integration is enabled for your customers to use. | | -| `integration_id` | *Optional[str]* | :heavy_minus_sign: | A Codat ID representing the integration. | fd321cb6-7963-4506-b873-e99593a45e30 | -| `is_beta` | *Optional[bool]* | :heavy_minus_sign: | `True` if the integration is currently in beta release. | | -| `is_offline_connector` | *Optional[bool]* | :heavy_minus_sign: | `True` if the integration is to an application installed and run locally on an SMBs computer. | | -| `key` | *str* | :heavy_check_mark: | A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys. | gbol | -| `logo_url` | *str* | :heavy_check_mark: | Static url for integration's logo. | | -| `name` | *str* | :heavy_check_mark: | Name of integration. | Xero | -| `source_id` | *Optional[str]* | :heavy_minus_sign: | A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`. | 35b92968-9851-4095-ad60-395c95cbcba4 | +# Integration + +An integration that Codat supports + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `data_provided_by` | *Optional[str]* | :heavy_minus_sign: | The name of the data provider. | | +| `datatype_features` | List[[shared.DataTypeFeature](../../models/shared/datatypefeature.md)] | :heavy_minus_sign: | N/A | | +| `enabled` | *bool* | :heavy_check_mark: | Whether this integration is enabled for your customers to use. | | +| `integration_id` | *Optional[str]* | :heavy_minus_sign: | A Codat ID representing the integration. | fd321cb6-7963-4506-b873-e99593a45e30 | +| `is_beta` | *Optional[bool]* | :heavy_minus_sign: | `True` if the integration is currently in beta release. | | +| `is_offline_connector` | *Optional[bool]* | :heavy_minus_sign: | `True` if the integration is to an application installed and run locally on an SMBs computer. | | +| `key` | *str* | :heavy_check_mark: | A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys. | gbol | +| `logo_url` | *str* | :heavy_check_mark: | Static url for integration's logo. | | +| `name` | *str* | :heavy_check_mark: | Name of integration. | Xero | +| `source_id` | *Optional[str]* | :heavy_minus_sign: | A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`. | 35b92968-9851-4095-ad60-395c95cbcba4 | | `source_type` | [Optional[shared.SourceType]](../../models/shared/sourcetype.md) | :heavy_minus_sign: | The type of platform of the connection. | Accounting | \ No newline at end of file diff --git a/platform/docs/models/shared/integrations.md b/platform/docs/models/shared/integrations.md index f178e35ba..b74acd8ff 100644 --- a/platform/docs/models/shared/integrations.md +++ b/platform/docs/models/shared/integrations.md @@ -1,12 +1,12 @@ -# Integrations - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | -| `page_number` | *int* | :heavy_check_mark: | Current page number. | | -| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | -| `results` | List[[shared.Integration](../../models/shared/integration.md)] | :heavy_minus_sign: | N/A | | +# Integrations + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | +| `page_number` | *int* | :heavy_check_mark: | Current page number. | | +| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | +| `results` | List[[shared.Integration](../../models/shared/integration.md)] | :heavy_minus_sign: | N/A | | | `total_results` | *int* | :heavy_check_mark: | Total number of items. | | \ No newline at end of file diff --git a/platform/docs/models/shared/issue.md b/platform/docs/models/shared/issue.md index 126d5c40f..9041fb830 100644 --- a/platform/docs/models/shared/issue.md +++ b/platform/docs/models/shared/issue.md @@ -1,12 +1,12 @@ -# Issue - -Details of a problem encountered during a data read. - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | -| `links` | [Optional[shared.IssueLinks]](../../models/shared/issuelinks.md) | :heavy_minus_sign: | N/A | | -| `message` | *Optional[str]* | :heavy_minus_sign: | A message describing the issue. | Something doesn't look right about these accounts from Xero. You can see more information in the logs. | +# Issue + +Details of a problem encountered during a data read. + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `links` | [Optional[shared.IssueLinks]](../../models/shared/issuelinks.md) | :heavy_minus_sign: | N/A | | +| `message` | *Optional[str]* | :heavy_minus_sign: | A message describing the issue. | Something doesn't look right about these accounts from Xero. You can see more information in the logs. | | `type` | *Optional[str]* | :heavy_minus_sign: | The type of issue. | warning.validation | \ No newline at end of file diff --git a/platform/docs/models/shared/issuelinks.md b/platform/docs/models/shared/issuelinks.md index 0b45b7e65..dd68df3d6 100644 --- a/platform/docs/models/shared/issuelinks.md +++ b/platform/docs/models/shared/issuelinks.md @@ -1,10 +1,10 @@ -# IssueLinks - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| `logs` | *Optional[str]* | :heavy_minus_sign: | A link to the validation logs, providing details on any errors or warnings encountered. | https://api.codat.io/companies/0498e921-9b53-4396-a412-4f2f5983b0a2/sync/{datasetId}/validation | -| `portal` | *Optional[str]* | :heavy_minus_sign: | A link to the company's past data read history in the Codat portal. | https://app.codat.io/companies/0498e921-9b53-4396-a412-4f2f5983b0a2/pull-history | +# IssueLinks + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| `logs` | *Optional[str]* | :heavy_minus_sign: | A link to the validation logs, providing details on any errors or warnings encountered. | https://api.codat.io/companies/0498e921-9b53-4396-a412-4f2f5983b0a2/sync/{datasetId}/validation | +| `portal` | *Optional[str]* | :heavy_minus_sign: | A link to the company's past data read history in the Codat portal. | https://app.codat.io/companies/0498e921-9b53-4396-a412-4f2f5983b0a2/pull-history | | `read_more` | *Optional[str]* | :heavy_minus_sign: | A link to Codat's documentation with additional information on how to troubleshoot this issue. | https://docs.codat.io/using-the-api/get-data-troubleshooting#warning.validation | \ No newline at end of file diff --git a/platform/docs/models/shared/links.md b/platform/docs/models/shared/links.md index 5f80d2652..b91889951 100644 --- a/platform/docs/models/shared/links.md +++ b/platform/docs/models/shared/links.md @@ -1,11 +1,11 @@ -# Links - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -| `current` | [shared.HalRef](../../models/shared/halref.md) | :heavy_check_mark: | N/A | -| `next` | [Optional[shared.HalRef]](../../models/shared/halref.md) | :heavy_minus_sign: | N/A | -| `previous` | [Optional[shared.HalRef]](../../models/shared/halref.md) | :heavy_minus_sign: | N/A | +# Links + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | +| `current` | [shared.HalRef](../../models/shared/halref.md) | :heavy_check_mark: | N/A | +| `next` | [Optional[shared.HalRef]](../../models/shared/halref.md) | :heavy_minus_sign: | N/A | +| `previous` | [Optional[shared.HalRef]](../../models/shared/halref.md) | :heavy_minus_sign: | N/A | | `self_` | [shared.HalRef](../../models/shared/halref.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/modifieddate.md b/platform/docs/models/shared/modifieddate.md index 535692632..ce4eeb648 100644 --- a/platform/docs/models/shared/modifieddate.md +++ b/platform/docs/models/shared/modifieddate.md @@ -1,8 +1,8 @@ -# ModifiedDate - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | +# ModifiedDate + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | | `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | \ No newline at end of file diff --git a/platform/docs/models/shared/paginginfo.md b/platform/docs/models/shared/paginginfo.md new file mode 100644 index 000000000..b72226e79 --- /dev/null +++ b/platform/docs/models/shared/paginginfo.md @@ -0,0 +1,11 @@ +# PagingInfo + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | +| `page_number` | *int* | :heavy_check_mark: | Current page number. | | +| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | +| `total_results` | *int* | :heavy_check_mark: | Total number of items. | | \ No newline at end of file diff --git a/platform/docs/models/shared/profile.md b/platform/docs/models/shared/profile.md index 778d651ed..f4e2e8796 100644 --- a/platform/docs/models/shared/profile.md +++ b/platform/docs/models/shared/profile.md @@ -1,16 +1,16 @@ -# Profile - -Describes your Codat client instance - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| ~~`api_key`~~ | *Optional[str]* | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

The API key for this Codat instance. | sartANTjHAkLdbyDfaynoTQb7pkmj6hXHmnQKMrB | -| ~~`confirm_company_name`~~ | *Optional[bool]* | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

`True` if the company name has been confirmed. | | -| `icon_url` | *Optional[str]* | :heavy_minus_sign: | Static url to your organization's icon. | https://client-images.codat.io/icon/042399f5-d104-4f38-9ce8-cac3524f4e88_3f5623af-d992-4c22-bc08-e58c520a8526.ico | -| `logo_url` | *Optional[str]* | :heavy_minus_sign: | Static url to your organization's logo. | https://client-images.codat.io/logo/042399f5-d104-4f38-9ce8-cac3524f4e88_5806cb1f-7342-4c0e-a0a8-99bfbc47b0ff.png | -| `name` | *str* | :heavy_check_mark: | The name given to the instance. | Bob's Burgers | -| `redirect_url` | *str* | :heavy_check_mark: | The redirect URL pasted on to the SMB once Codat's [Hosted Link](https://docs.codat.io/auth-flow/authorize-hosted-link) has been completed by the SMB. | https://bobs-burgers.{countrySuffix}/{companyId} | +# Profile + +Describes your Codat client instance + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ~~`api_key`~~ | *Optional[str]* | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

The API key for this Codat instance. | sartANTjHAkLdbyDfaynoTQb7pkmj6hXHmnQKMrB | +| ~~`confirm_company_name`~~ | *Optional[bool]* | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

`True` if the company name has been confirmed. | | +| `icon_url` | *Optional[str]* | :heavy_minus_sign: | Static url to your organization's icon. | https://client-images.codat.io/icon/042399f5-d104-4f38-9ce8-cac3524f4e88_3f5623af-d992-4c22-bc08-e58c520a8526.ico | +| `logo_url` | *Optional[str]* | :heavy_minus_sign: | Static url to your organization's logo. | https://client-images.codat.io/logo/042399f5-d104-4f38-9ce8-cac3524f4e88_5806cb1f-7342-4c0e-a0a8-99bfbc47b0ff.png | +| `name` | *str* | :heavy_check_mark: | The name given to the instance. | Bob's Burgers | +| `redirect_url` | *str* | :heavy_check_mark: | The redirect URL pasted on to the SMB once Codat's [Hosted Link](https://docs.codat.io/auth-flow/authorize-hosted-link) has been completed by the SMB. | https://bobs-burgers.{countrySuffix}/{companyId} | | `white_list_urls` | List[*str*] | :heavy_minus_sign: | A list of urls that are allowed to communicate with Codat. If empty any url is allowed to communicate with Codat. | | \ No newline at end of file diff --git a/platform/docs/models/shared/pulloperation.md b/platform/docs/models/shared/pulloperation.md index bea7bb1d5..4f38463eb 100644 --- a/platform/docs/models/shared/pulloperation.md +++ b/platform/docs/models/shared/pulloperation.md @@ -1,22 +1,22 @@ -# PullOperation - -Information about a queued, in progress or completed pull operation. -*Formally called `dataset`* - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier of the company associated to this pull operation. | 22ece347-e5f6-4896-95e0-35a4c7f17023 | -| `completed` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier of the connection associated to this pull operation. | 50830828-7d39-4367-b0eb-5ddb2de5faa5 | -| `data_type` | *str* | :heavy_check_mark: | The data type you are requesting in a pull operation. | | -| `error_message` | *OptionalNullable[str]* | :heavy_minus_sign: | A message about a transient or persistent error returned by Codat or the source platform. | | -| `id` | *str* | :heavy_check_mark: | Unique identifier of the pull operation. | 943accd0-4247-42d8-865b-363c8629e1da | -| `is_completed` | *bool* | :heavy_check_mark: | `True` if the pull operation is completed successfully. The `isCompleted` property is not queryable. To filter failed pull operations, query by `status!=Complete&&status!=NotSupported` instead. | | -| `is_errored` | *bool* | :heavy_check_mark: | `True` if the pull operation entered an error state. | | -| `progress` | *int* | :heavy_check_mark: | An integer signifying the progress of the pull operation. | | -| `requested` | *str* | :heavy_check_mark: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `status` | [shared.DatasetStatus](../../models/shared/datasetstatus.md) | :heavy_check_mark: | The current status of the dataset. | | +# PullOperation + +Information about a queued, in progress or completed pull operation. +*Formally called `dataset`* + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier of the company associated to this pull operation. | 22ece347-e5f6-4896-95e0-35a4c7f17023 | +| `completed` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier of the connection associated to this pull operation. | 50830828-7d39-4367-b0eb-5ddb2de5faa5 | +| `data_type` | *str* | :heavy_check_mark: | The data type you are requesting in a pull operation. | | +| `error_message` | *OptionalNullable[str]* | :heavy_minus_sign: | A message about a transient or persistent error returned by Codat or the source platform. | | +| `id` | *str* | :heavy_check_mark: | Unique identifier of the pull operation. | 943accd0-4247-42d8-865b-363c8629e1da | +| `is_completed` | *bool* | :heavy_check_mark: | `True` if the pull operation is completed successfully. The `isCompleted` property is not queryable. To filter failed pull operations, query by `status!=Complete&&status!=NotSupported` instead. | | +| `is_errored` | *bool* | :heavy_check_mark: | `True` if the pull operation entered an error state. | | +| `progress` | *int* | :heavy_check_mark: | An integer signifying the progress of the pull operation. | | +| `requested` | *str* | :heavy_check_mark: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `status` | [shared.DatasetStatus](../../models/shared/datasetstatus.md) | :heavy_check_mark: | The current status of the dataset. | | | `status_description` | *OptionalNullable[str]* | :heavy_minus_sign: | Additional information about the dataset status. | Paused until 2022-10-23T00:00:00.000Z | \ No newline at end of file diff --git a/platform/docs/models/shared/pulloperations.md b/platform/docs/models/shared/pulloperations.md index a5761e0aa..1c994a999 100644 --- a/platform/docs/models/shared/pulloperations.md +++ b/platform/docs/models/shared/pulloperations.md @@ -1,12 +1,12 @@ -# PullOperations - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | -| `page_number` | *int* | :heavy_check_mark: | Current page number. | | -| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | -| `results` | List[[shared.PullOperation](../../models/shared/pulloperation.md)] | :heavy_minus_sign: | N/A | | +# PullOperations + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | +| `page_number` | *int* | :heavy_check_mark: | Current page number. | | +| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | +| `results` | List[[shared.PullOperation](../../models/shared/pulloperation.md)] | :heavy_minus_sign: | N/A | | | `total_results` | *int* | :heavy_check_mark: | Total number of items. | | \ No newline at end of file diff --git a/platform/docs/models/shared/pushchangetype.md b/platform/docs/models/shared/pushchangetype.md index c2aab6319..73593e22c 100644 --- a/platform/docs/models/shared/pushchangetype.md +++ b/platform/docs/models/shared/pushchangetype.md @@ -1,22 +1,22 @@ -# PushChangeType - -Type of change being applied to record in third party platform. - -## Example Usage - -```python -from codat_platform.models.shared import PushChangeType - -value = PushChangeType.UNKNOWN -``` - - -## Values - -| Name | Value | -| --------------------- | --------------------- | -| `UNKNOWN` | Unknown | -| `CREATED` | Created | -| `MODIFIED` | Modified | -| `DELETED` | Deleted | +# PushChangeType + +Type of change being applied to record in third party platform. + +## Example Usage + +```python +from codat_platform.models.shared import PushChangeType + +value = PushChangeType.UNKNOWN +``` + + +## Values + +| Name | Value | +| --------------------- | --------------------- | +| `UNKNOWN` | Unknown | +| `CREATED` | Created | +| `MODIFIED` | Modified | +| `DELETED` | Deleted | | `ATTACHMENT_UPLOADED` | AttachmentUploaded | \ No newline at end of file diff --git a/platform/docs/models/shared/pushfieldvalidation.md b/platform/docs/models/shared/pushfieldvalidation.md index d3558cfad..b10ead92d 100644 --- a/platform/docs/models/shared/pushfieldvalidation.md +++ b/platform/docs/models/shared/pushfieldvalidation.md @@ -1,10 +1,11 @@ -# PushFieldValidation - - -## Fields - -| Field | Type | Required | Description | -| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | -| `details` | *str* | :heavy_check_mark: | Details on the validation issue. | -| `field` | *Optional[str]* | :heavy_minus_sign: | Field name that resulted in the validation issue. | +# PushFieldValidation + + +## Fields + +| Field | Type | Required | Description | +| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | +| `details` | *str* | :heavy_check_mark: | Details on the validation issue. | +| `field` | *Optional[str]* | :heavy_minus_sign: | Field name that resulted in the validation issue. | | `ref` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique reference identifier for the validation issue. | \ No newline at end of file diff --git a/platform/docs/models/shared/pushoperation.md b/platform/docs/models/shared/pushoperation.md index d01e17840..415430ac6 100644 --- a/platform/docs/models/shared/pushoperation.md +++ b/platform/docs/models/shared/pushoperation.md @@ -1,20 +1,20 @@ -# PushOperation - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `changes` | List[[shared.PushOperationChange](../../models/shared/pushoperationchange.md)] | :heavy_minus_sign: | Contains a single entry that communicates which record has changed and the manner in which it changed. | | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `completed_on_utc` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | -| `error_message` | *OptionalNullable[str]* | :heavy_minus_sign: | A message about the error. | | -| `push_operation_key` | *str* | :heavy_check_mark: | A unique identifier generated by Codat to represent this single push operation. This identifier can be used to track the status of the push, and should be persisted. | | -| `requested_on_utc` | *str* | :heavy_check_mark: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `status` | [shared.PushOperationStatus](../../models/shared/pushoperationstatus.md) | :heavy_check_mark: | The current status of the push operation. | | -| `status_code` | *int* | :heavy_check_mark: | Push status code. | | -| `timeout_in_minutes` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | -| ~~`timeout_in_seconds`~~ | *OptionalNullable[int]* | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

Number of seconds the push operation must complete within before it times out. | | +# PushOperation + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `changes` | List[[shared.PushOperationChange](../../models/shared/pushoperationchange.md)] | :heavy_minus_sign: | Contains a single entry that communicates which record has changed and the manner in which it changed. | | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `completed_on_utc` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | +| `error_message` | *OptionalNullable[str]* | :heavy_minus_sign: | A message about the error. | | +| `push_operation_key` | *str* | :heavy_check_mark: | A unique identifier generated by Codat to represent this single push operation. This identifier can be used to track the status of the push, and should be persisted. | | +| `requested_on_utc` | *str* | :heavy_check_mark: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `status` | [shared.PushOperationStatus](../../models/shared/pushoperationstatus.md) | :heavy_check_mark: | The current status of the push operation. | | +| `status_code` | *int* | :heavy_check_mark: | Push status code. | | +| `timeout_in_minutes` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | +| ~~`timeout_in_seconds`~~ | *OptionalNullable[int]* | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

Number of seconds the push operation must complete within before it times out. | | | `validation` | [Optional[shared.Validation]](../../models/shared/validation.md) | :heavy_minus_sign: | A human-readable object describing validation decisions Codat has made when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here. | | \ No newline at end of file diff --git a/platform/docs/models/shared/pushoperationchange.md b/platform/docs/models/shared/pushoperationchange.md index d5516b5c7..ef8fa0986 100644 --- a/platform/docs/models/shared/pushoperationchange.md +++ b/platform/docs/models/shared/pushoperationchange.md @@ -1,10 +1,10 @@ -# PushOperationChange - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `attachment_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier for the attachment created otherwise null. | -| `record_ref` | [Optional[shared.PushOperationRef]](../../models/shared/pushoperationref.md) | :heavy_minus_sign: | N/A | -| `type` | [Optional[shared.PushChangeType]](../../models/shared/pushchangetype.md) | :heavy_minus_sign: | Type of change being applied to record in third party platform. | \ No newline at end of file +# PushOperationChange + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `attachment_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier for the attachment created otherwise null. | +| `record_ref` | [Optional[shared.PushOperationRef]](../../models/shared/pushoperationref.md) | :heavy_minus_sign: | N/A | +| `type` | [Optional[shared.PushChangeType]](../../models/shared/pushchangetype.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/pushoperationref.md b/platform/docs/models/shared/pushoperationref.md index 7c26e1c4f..f7efa342a 100644 --- a/platform/docs/models/shared/pushoperationref.md +++ b/platform/docs/models/shared/pushoperationref.md @@ -1,9 +1,10 @@ -# PushOperationRef - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for a push operation. | | \ No newline at end of file +# PushOperationRef + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | +| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for a push operation. | \ No newline at end of file diff --git a/platform/docs/models/shared/pushoperations.md b/platform/docs/models/shared/pushoperations.md index 6a06b9c2b..776ac813c 100644 --- a/platform/docs/models/shared/pushoperations.md +++ b/platform/docs/models/shared/pushoperations.md @@ -1,12 +1,12 @@ -# PushOperations - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | -| `page_number` | *int* | :heavy_check_mark: | Current page number. | | -| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | -| `results` | List[[shared.PushOperation](../../models/shared/pushoperation.md)] | :heavy_minus_sign: | N/A | | +# PushOperations + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | +| `page_number` | *int* | :heavy_check_mark: | Current page number. | | +| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | +| `results` | List[[shared.PushOperation](../../models/shared/pushoperation.md)] | :heavy_minus_sign: | N/A | | | `total_results` | *int* | :heavy_check_mark: | Total number of items. | | \ No newline at end of file diff --git a/platform/docs/models/shared/pushoperationstatus.md b/platform/docs/models/shared/pushoperationstatus.md index f0e1d0fe8..abf9c05e2 100644 --- a/platform/docs/models/shared/pushoperationstatus.md +++ b/platform/docs/models/shared/pushoperationstatus.md @@ -1,21 +1,21 @@ -# PushOperationStatus - -The current status of the push operation. - -## Example Usage - -```python -from codat_platform.models.shared import PushOperationStatus - -value = PushOperationStatus.PENDING -``` - - -## Values - -| Name | Value | -| ----------- | ----------- | -| `PENDING` | Pending | -| `FAILED` | Failed | -| `SUCCESS` | Success | +# PushOperationStatus + +The current status of the push operation. + +## Example Usage + +```python +from codat_platform.models.shared import PushOperationStatus + +value = PushOperationStatus.PENDING +``` + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `PENDING` | Pending | +| `FAILED` | Failed | +| `SUCCESS` | Success | | `TIMED_OUT` | TimedOut | \ No newline at end of file diff --git a/platform/docs/models/shared/pushoption.md b/platform/docs/models/shared/pushoption.md index e908d0b28..9bff99cd3 100644 --- a/platform/docs/models/shared/pushoption.md +++ b/platform/docs/models/shared/pushoption.md @@ -1,14 +1,14 @@ -# PushOption - - -## Fields - -| Field | Type | Required | Description | -| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | -| `description` | *Optional[str]* | :heavy_minus_sign: | A description of the property. | -| `display_name` | *str* | :heavy_check_mark: | The property's display name. | -| `options` | List[[shared.PushOptionChoice](../../models/shared/pushoptionchoice.md)] | :heavy_minus_sign: | N/A | -| `properties` | Dict[str, [shared.PushOptionProperty](../../models/shared/pushoptionproperty.md)] | :heavy_minus_sign: | N/A | -| `required` | *bool* | :heavy_check_mark: | The property is required if `True`. | -| `type` | [shared.PushOptionType](../../models/shared/pushoptiontype.md) | :heavy_check_mark: | The option type. | +# PushOption + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | +| `description` | *Optional[str]* | :heavy_minus_sign: | A description of the property. | +| `display_name` | *str* | :heavy_check_mark: | The property's display name. | +| `options` | List[[shared.PushOptionChoice](../../models/shared/pushoptionchoice.md)] | :heavy_minus_sign: | N/A | +| `properties` | Dict[str, [shared.PushOptionProperty](../../models/shared/pushoptionproperty.md)] | :heavy_minus_sign: | N/A | +| `required` | *bool* | :heavy_check_mark: | The property is required if `True`. | +| `type` | [shared.PushOptionType](../../models/shared/pushoptiontype.md) | :heavy_check_mark: | The option type. | | `validation` | [Optional[shared.PushValidationInfo]](../../models/shared/pushvalidationinfo.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/pushoptionchoice.md b/platform/docs/models/shared/pushoptionchoice.md index 44e988b26..8c993a020 100644 --- a/platform/docs/models/shared/pushoptionchoice.md +++ b/platform/docs/models/shared/pushoptionchoice.md @@ -1,12 +1,12 @@ -# PushOptionChoice - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | -| `description` | *Optional[str]* | :heavy_minus_sign: | A description of the property. | -| `display_name` | *Optional[str]* | :heavy_minus_sign: | The property's display name. | -| `required` | *Optional[bool]* | :heavy_minus_sign: | The property is required if `True`. | -| `type` | [Optional[shared.PushOptionType]](../../models/shared/pushoptiontype.md) | :heavy_minus_sign: | The option type. | +# PushOptionChoice + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `description` | *Optional[str]* | :heavy_minus_sign: | A description of the property. | +| `display_name` | *Optional[str]* | :heavy_minus_sign: | The property's display name. | +| `required` | *Optional[bool]* | :heavy_minus_sign: | The property is required if `True`. | +| `type` | [Optional[shared.PushOptionType]](../../models/shared/pushoptiontype.md) | :heavy_minus_sign: | The option type. | | `value` | *Optional[str]* | :heavy_minus_sign: | Allowed value for field. | \ No newline at end of file diff --git a/platform/docs/models/shared/pushoptionproperty.md b/platform/docs/models/shared/pushoptionproperty.md index 2bedd19d3..02801135b 100644 --- a/platform/docs/models/shared/pushoptionproperty.md +++ b/platform/docs/models/shared/pushoptionproperty.md @@ -1,14 +1,14 @@ -# PushOptionProperty - - -## Fields - -| Field | Type | Required | Description | -| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | -| `description` | *str* | :heavy_check_mark: | A description of the property. | -| `display_name` | *str* | :heavy_check_mark: | The property's display name. | -| `options` | List[[shared.PushOptionChoice](../../models/shared/pushoptionchoice.md)] | :heavy_minus_sign: | N/A | -| `properties` | Dict[str, [shared.PushOptionProperty](../../models/shared/pushoptionproperty.md)] | :heavy_minus_sign: | N/A | -| `required` | *bool* | :heavy_check_mark: | The property is required if `True`. | -| `type` | [shared.PushOptionType](../../models/shared/pushoptiontype.md) | :heavy_check_mark: | The option type. | +# PushOptionProperty + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | +| `description` | *str* | :heavy_check_mark: | A description of the property. | +| `display_name` | *str* | :heavy_check_mark: | The property's display name. | +| `options` | List[[shared.PushOptionChoice](../../models/shared/pushoptionchoice.md)] | :heavy_minus_sign: | N/A | +| `properties` | Dict[str, [shared.PushOptionProperty](../../models/shared/pushoptionproperty.md)] | :heavy_minus_sign: | N/A | +| `required` | *bool* | :heavy_check_mark: | The property is required if `True`. | +| `type` | [shared.PushOptionType](../../models/shared/pushoptiontype.md) | :heavy_check_mark: | The option type. | | `validation` | [Optional[shared.PushValidationInfo]](../../models/shared/pushvalidationinfo.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/pushoptiontype.md b/platform/docs/models/shared/pushoptiontype.md index c3a5be858..90f84bcdb 100644 --- a/platform/docs/models/shared/pushoptiontype.md +++ b/platform/docs/models/shared/pushoptiontype.md @@ -1,25 +1,23 @@ -# PushOptionType - -The option type. - -## Example Usage - -```python -from codat_platform.models.shared import PushOptionType - -value = PushOptionType.ARRAY -``` - - -## Values - -| Name | Value | -| ------------ | ------------ | -| `ARRAY` | Array | -| `OBJECT` | Object | -| `STRING` | String | -| `NUMBER` | Number | -| `BOOLEAN` | Boolean | -| `DATE_TIME` | DateTime | -| `FILE` | File | +# PushOptionType + +## Example Usage + +```python +from codat_platform.models.shared import PushOptionType + +value = PushOptionType.ARRAY +``` + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `ARRAY` | Array | +| `OBJECT` | Object | +| `STRING` | String | +| `NUMBER` | Number | +| `BOOLEAN` | Boolean | +| `DATE_TIME` | DateTime | +| `FILE` | File | | `MULTI_PART` | MultiPart | \ No newline at end of file diff --git a/platform/docs/models/shared/pushvalidationinfo.md b/platform/docs/models/shared/pushvalidationinfo.md index 110eb3f76..ad9013935 100644 --- a/platform/docs/models/shared/pushvalidationinfo.md +++ b/platform/docs/models/shared/pushvalidationinfo.md @@ -1,9 +1,10 @@ -# PushValidationInfo - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | -| `information` | List[[shared.PushFieldValidation](../../models/shared/pushfieldvalidation.md)] | :heavy_minus_sign: | N/A | +# PushValidationInfo + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | +| `information` | List[[shared.PushFieldValidation](../../models/shared/pushfieldvalidation.md)] | :heavy_minus_sign: | N/A | | `warnings` | List[[shared.PushFieldValidation](../../models/shared/pushfieldvalidation.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/readcompletedwebhook.md b/platform/docs/models/shared/readcompletedwebhook.md index b48235f9e..afcea7811 100644 --- a/platform/docs/models/shared/readcompletedwebhook.md +++ b/platform/docs/models/shared/readcompletedwebhook.md @@ -1,11 +1,11 @@ -# ReadCompletedWebhook - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | | -| `generated_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the event. | 743ec94a-8aa4-44bb-8bd4-e1855ee0e74b | +# ReadCompletedWebhook + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | | +| `generated_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the event. | 743ec94a-8aa4-44bb-8bd4-e1855ee0e74b | | `payload` | [Optional[shared.ReadCompletedWebhookPayload]](../../models/shared/readcompletedwebhookpayload.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/shared/readcompletedwebhookpayload.md b/platform/docs/models/shared/readcompletedwebhookpayload.md index b95b01755..05b9a76f0 100644 --- a/platform/docs/models/shared/readcompletedwebhookpayload.md +++ b/platform/docs/models/shared/readcompletedwebhookpayload.md @@ -1,10 +1,10 @@ -# ReadCompletedWebhookPayload - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `data_types` | List[[shared.DataTypeReadSummary](../../models/shared/datatypereadsummary.md)] | :heavy_minus_sign: | N/A | | -| `modified_from_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `reference_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file +# ReadCompletedWebhookPayload + + +## Fields + +| Field | Type | Required | Description | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `data_types` | List[[shared.DataTypeReadSummary](../../models/shared/datatypereadsummary.md)] | :heavy_minus_sign: | N/A | +| `modified_from_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | +| `reference_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/refreshproductdatarequest.md b/platform/docs/models/shared/refreshproductdatarequest.md new file mode 100644 index 000000000..62a2279ad --- /dev/null +++ b/platform/docs/models/shared/refreshproductdatarequest.md @@ -0,0 +1,9 @@ +# RefreshProductDataRequest + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | +| `data_types` | List[*str*] | :heavy_minus_sign: | One or more data types to refresh for the product. | \ No newline at end of file diff --git a/platform/docs/models/shared/schemadatatype.md b/platform/docs/models/shared/schemadatatype.md index 34468c90f..fb7e8fa77 100644 --- a/platform/docs/models/shared/schemadatatype.md +++ b/platform/docs/models/shared/schemadatatype.md @@ -1,60 +1,60 @@ -# SchemaDataType - -Available data types - -## Example Usage - -```python -from codat_platform.models.shared import SchemaDataType - -value = SchemaDataType.ACCOUNT_TRANSACTIONS -``` - - -## Values - -| Name | Value | -| -------------------------------- | -------------------------------- | -| `ACCOUNT_TRANSACTIONS` | accountTransactions | -| `BALANCE_SHEET` | balanceSheet | -| `BANK_ACCOUNTS` | bankAccounts | -| `BANK_TRANSACTIONS` | bankTransactions | -| `BILL_CREDIT_NOTES` | billCreditNotes | -| `BILL_PAYMENTS` | billPayments | -| `BILLS` | bills | -| `CASH_FLOW_STATEMENT` | cashFlowStatement | -| `CHART_OF_ACCOUNTS` | chartOfAccounts | -| `COMPANY` | company | -| `CREDIT_NOTES` | creditNotes | -| `CUSTOMERS` | customers | -| `DIRECT_COSTS` | directCosts | -| `DIRECT_INCOMES` | directIncomes | -| `INVOICES` | invoices | -| `ITEM_RECEIPTS` | itemReceipts | -| `ITEMS` | items | -| `JOURNAL_ENTRIES` | journalEntries | -| `JOURNALS` | journals | -| `PAYMENT_METHODS` | paymentMethods | -| `PAYMENTS` | payments | -| `PROFIT_AND_LOSS` | profitAndLoss | -| `PURCHASE_ORDERS` | purchaseOrders | -| `SALES_ORDERS` | salesOrders | -| `SUPPLIERS` | suppliers | -| `TAX_RATES` | taxRates | -| `TRACKING_CATEGORIES` | trackingCategories | -| `TRANSFERS` | transfers | -| `BANKING_ACCOUNT_BALANCES` | banking-accountBalances | -| `BANKING_ACCOUNTS` | banking-accounts | -| `BANKING_TRANSACTION_CATEGORIES` | banking-transactionCategories | -| `BANKING_TRANSACTIONS` | banking-transactions | -| `COMMERCE_COMPANY_INFO` | commerce-companyInfo | -| `COMMERCE_CUSTOMERS` | commerce-customers | -| `COMMERCE_DISPUTES` | commerce-disputes | -| `COMMERCE_LOCATIONS` | commerce-locations | -| `COMMERCE_ORDERS` | commerce-orders | -| `COMMERCE_PAYMENT_METHODS` | commerce-paymentMethods | -| `COMMERCE_PAYMENTS` | commerce-payments | -| `COMMERCE_PRODUCT_CATEGORIES` | commerce-productCategories | -| `COMMERCE_PRODUCTS` | commerce-products | -| `COMMERCE_TAX_COMPONENTS` | commerce-taxComponents | +# SchemaDataType + +Available data types + +## Example Usage + +```python +from codat_platform.models.shared import SchemaDataType + +value = SchemaDataType.ACCOUNT_TRANSACTIONS +``` + + +## Values + +| Name | Value | +| -------------------------------- | -------------------------------- | +| `ACCOUNT_TRANSACTIONS` | accountTransactions | +| `BALANCE_SHEET` | balanceSheet | +| `BANK_ACCOUNTS` | bankAccounts | +| `BANK_TRANSACTIONS` | bankTransactions | +| `BILL_CREDIT_NOTES` | billCreditNotes | +| `BILL_PAYMENTS` | billPayments | +| `BILLS` | bills | +| `CASH_FLOW_STATEMENT` | cashFlowStatement | +| `CHART_OF_ACCOUNTS` | chartOfAccounts | +| `COMPANY` | company | +| `CREDIT_NOTES` | creditNotes | +| `CUSTOMERS` | customers | +| `DIRECT_COSTS` | directCosts | +| `DIRECT_INCOMES` | directIncomes | +| `INVOICES` | invoices | +| `ITEM_RECEIPTS` | itemReceipts | +| `ITEMS` | items | +| `JOURNAL_ENTRIES` | journalEntries | +| `JOURNALS` | journals | +| `PAYMENT_METHODS` | paymentMethods | +| `PAYMENTS` | payments | +| `PROFIT_AND_LOSS` | profitAndLoss | +| `PURCHASE_ORDERS` | purchaseOrders | +| `SALES_ORDERS` | salesOrders | +| `SUPPLIERS` | suppliers | +| `TAX_RATES` | taxRates | +| `TRACKING_CATEGORIES` | trackingCategories | +| `TRANSFERS` | transfers | +| `BANKING_ACCOUNT_BALANCES` | banking-accountBalances | +| `BANKING_ACCOUNTS` | banking-accounts | +| `BANKING_TRANSACTION_CATEGORIES` | banking-transactionCategories | +| `BANKING_TRANSACTIONS` | banking-transactions | +| `COMMERCE_COMPANY_INFO` | commerce-companyInfo | +| `COMMERCE_CUSTOMERS` | commerce-customers | +| `COMMERCE_DISPUTES` | commerce-disputes | +| `COMMERCE_LOCATIONS` | commerce-locations | +| `COMMERCE_ORDERS` | commerce-orders | +| `COMMERCE_PAYMENT_METHODS` | commerce-paymentMethods | +| `COMMERCE_PAYMENTS` | commerce-payments | +| `COMMERCE_PRODUCT_CATEGORIES` | commerce-productCategories | +| `COMMERCE_PRODUCTS` | commerce-products | +| `COMMERCE_TAX_COMPONENTS` | commerce-taxComponents | | `COMMERCE_TRANSACTIONS` | commerce-transactions | \ No newline at end of file diff --git a/platform/docs/models/shared/security.md b/platform/docs/models/shared/security.md index 2b68bd0e7..e7a8e4384 100644 --- a/platform/docs/models/shared/security.md +++ b/platform/docs/models/shared/security.md @@ -1,8 +1,8 @@ -# Security - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------ | ------------------------------ | ------------------------------ | ------------------------------ | ------------------------------ | -| `auth_header` | *str* | :heavy_check_mark: | N/A | Basic BASE_64_ENCODED(API_KEY) | \ No newline at end of file +# Security + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `auth_header` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/setcompanysyncsettingsrequest.md b/platform/docs/models/shared/setcompanysyncsettingsrequest.md new file mode 100644 index 000000000..9d84dfcc6 --- /dev/null +++ b/platform/docs/models/shared/setcompanysyncsettingsrequest.md @@ -0,0 +1,10 @@ +# SetCompanySyncSettingsRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `overrides_defaults` | *Optional[bool]* | :heavy_minus_sign: | Set to `True` if you want to override the default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings). | | +| `settings` | List[[shared.SyncSetting](../../models/shared/syncsetting.md)] | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/platform/docs/models/shared/sourcetype.md b/platform/docs/models/shared/sourcetype.md index 6ca0721d0..c434394cf 100644 --- a/platform/docs/models/shared/sourcetype.md +++ b/platform/docs/models/shared/sourcetype.md @@ -1,24 +1,24 @@ -# SourceType - -The type of platform of the connection. - -## Example Usage - -```python -from codat_platform.models.shared import SourceType - -value = SourceType.ACCOUNTING -``` - - -## Values - -| Name | Value | -| ------------ | ------------ | -| `ACCOUNTING` | Accounting | -| `BANKING` | Banking | -| `BANK_FEED` | BankFeed | -| `COMMERCE` | Commerce | -| `EXPENSE` | Expense | -| `OTHER` | Other | +# SourceType + +The type of platform of the connection. + +## Example Usage + +```python +from codat_platform.models.shared import SourceType + +value = SourceType.ACCOUNTING +``` + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `ACCOUNTING` | Accounting | +| `BANKING` | Banking | +| `BANK_FEED` | BankFeed | +| `COMMERCE` | Commerce | +| `EXPENSE` | Expense | +| `OTHER` | Other | | `UNKNOWN` | Unknown | \ No newline at end of file diff --git a/platform/docs/models/shared/status.md b/platform/docs/models/shared/status.md index 25ddb4d97..35677a6a3 100644 --- a/platform/docs/models/shared/status.md +++ b/platform/docs/models/shared/status.md @@ -1,38 +1,36 @@ -# Status - -The current status of the dataset. - -## Example Usage - -```python -from codat_platform.models.shared import Status - -value = Status.INITIAL -``` - - -## Values - -| Name | Value | -| ---------------------- | ---------------------- | -| `INITIAL` | Initial | -| `QUEUED` | Queued | -| `FETCHING` | Fetching | -| `MAP_QUEUED` | MapQueued | -| `MAPPING` | Mapping | -| `COMPLETE` | Complete | -| `FETCH_ERROR` | FetchError | -| `MAP_ERROR` | MapError | -| `INTERNAL_ERROR` | InternalError | -| `PROCESSING_QUEUED` | ProcessingQueued | -| `PROCESSING` | Processing | -| `PROCESSING_ERROR` | ProcessingError | -| `VALIDATION_QUEUED` | ValidationQueued | -| `VALIDATING` | Validating | -| `VALIDATION_ERROR` | ValidationError | -| `AUTH_ERROR` | AuthError | -| `CANCELLED` | Cancelled | -| `NOT_SUPPORTED` | NotSupported | -| `RATE_LIMIT_ERROR` | RateLimitError | -| `PERMISSIONS_ERROR` | PermissionsError | +# Status + +## Example Usage + +```python +from codat_platform.models.shared import Status + +value = Status.INITIAL +``` + + +## Values + +| Name | Value | +| ---------------------- | ---------------------- | +| `INITIAL` | Initial | +| `QUEUED` | Queued | +| `FETCHING` | Fetching | +| `MAP_QUEUED` | MapQueued | +| `MAPPING` | Mapping | +| `COMPLETE` | Complete | +| `FETCH_ERROR` | FetchError | +| `MAP_ERROR` | MapError | +| `INTERNAL_ERROR` | InternalError | +| `PROCESSING_QUEUED` | ProcessingQueued | +| `PROCESSING` | Processing | +| `PROCESSING_ERROR` | ProcessingError | +| `VALIDATION_QUEUED` | ValidationQueued | +| `VALIDATING` | Validating | +| `VALIDATION_ERROR` | ValidationError | +| `AUTH_ERROR` | AuthError | +| `CANCELLED` | Cancelled | +| `NOT_SUPPORTED` | NotSupported | +| `RATE_LIMIT_ERROR` | RateLimitError | +| `PERMISSIONS_ERROR` | PermissionsError | | `PREREQUISITE_NOT_MET` | PrerequisiteNotMet | \ No newline at end of file diff --git a/platform/docs/models/shared/supplementaldataconfiguration.md b/platform/docs/models/shared/supplementaldataconfiguration.md index c9ea5c701..d0691cf2d 100644 --- a/platform/docs/models/shared/supplementaldataconfiguration.md +++ b/platform/docs/models/shared/supplementaldataconfiguration.md @@ -1,8 +1,8 @@ -# SupplementalDataConfiguration - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | +# SupplementalDataConfiguration + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | `supplemental_data_config` | Dict[str, [shared.SupplementalDataSourceConfiguration](../../models/shared/supplementaldatasourceconfiguration.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/supplementaldatasourceconfiguration.md b/platform/docs/models/shared/supplementaldatasourceconfiguration.md index ec00fd9a9..4a9f98beb 100644 --- a/platform/docs/models/shared/supplementaldatasourceconfiguration.md +++ b/platform/docs/models/shared/supplementaldatasourceconfiguration.md @@ -1,12 +1,12 @@ -# SupplementalDataSourceConfiguration - -The client's defined name for the object. - - -## Fields - -| Field | Type | Required | Description | -| ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | -| `data_source` | *Optional[str]* | :heavy_minus_sign: | The underlying endpoint of the source system which the configuration is targeting. | -| `pull_data` | Dict[str, *str*] | :heavy_minus_sign: | The additional properties that are required when pulling records. | +# SupplementalDataSourceConfiguration + +The client's defined name for the object. + + +## Fields + +| Field | Type | Required | Description | +| ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| `data_source` | *Optional[str]* | :heavy_minus_sign: | The underlying endpoint of the source system which the configuration is targeting. | +| `pull_data` | Dict[str, *str*] | :heavy_minus_sign: | The additional properties that are required when pulling records. | | `push_data` | Dict[str, *str*] | :heavy_minus_sign: | The additional properties that are required to create and/or update records. | \ No newline at end of file diff --git a/platform/docs/models/shared/supportedfeature.md b/platform/docs/models/shared/supportedfeature.md index 083b8816e..5d1592e58 100644 --- a/platform/docs/models/shared/supportedfeature.md +++ b/platform/docs/models/shared/supportedfeature.md @@ -1,9 +1,9 @@ -# SupportedFeature - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | -| `feature_state` | [shared.FeatureState](../../models/shared/featurestate.md) | :heavy_check_mark: | The current release state of the feature. | Release | -| `feature_type` | [shared.FeatureType](../../models/shared/featuretype.md) | :heavy_check_mark: | The type of feature. | Get | \ No newline at end of file +# SupportedFeature + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | +| `feature_state` | [shared.FeatureState](../../models/shared/featurestate.md) | :heavy_check_mark: | N/A | +| `feature_type` | [shared.FeatureType](../../models/shared/featuretype.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/syncsetting.md b/platform/docs/models/shared/syncsetting.md index 3a2888cf5..2104d4a4e 100644 --- a/platform/docs/models/shared/syncsetting.md +++ b/platform/docs/models/shared/syncsetting.md @@ -1,17 +1,17 @@ -# SyncSetting - -Describes how often, and how much history, should be fetched for the given data type when a pull operation is queued. - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `data_type` | [shared.DataType](../../models/shared/datatype.md) | :heavy_check_mark: | Available data types | invoices | -| `fetch_on_first_link` | *bool* | :heavy_check_mark: | Whether this data type should be queued after a company has authorized a connection. | | -| `is_locked` | *Optional[bool]* | :heavy_minus_sign: | `True` if the [sync setting](https://docs.codat.io/knowledge-base/advanced-sync-settings) is locked. | | -| `months_to_sync` | *Optional[int]* | :heavy_minus_sign: | Months of data to fetch, for report data types (`balanceSheet` & `profitAndLoss`) only. | 24 | -| `sync_from_utc` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `sync_from_window` | *Optional[int]* | :heavy_minus_sign: | Number of months of data to be fetched. Set this *or* `syncFromUTC`. | 24 | -| `sync_order` | *int* | :heavy_check_mark: | The sync in which data types are queued for a sync. | | +# SyncSetting + +Describes how often, and how much history, should be fetched for the given data type when a pull operation is queued. + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `data_type` | [shared.DataType](../../models/shared/datatype.md) | :heavy_check_mark: | Available data types | invoices | +| `fetch_on_first_link` | *bool* | :heavy_check_mark: | Whether this data type should be queued after a company has authorized a connection. | | +| `is_locked` | *Optional[bool]* | :heavy_minus_sign: | `True` if the [sync setting](https://docs.codat.io/knowledge-base/advanced-sync-settings) is locked. | | +| `months_to_sync` | *Optional[int]* | :heavy_minus_sign: | Months of data to fetch, for report data types (`balanceSheet` & `profitAndLoss`) only. | 24 | +| `sync_from_utc` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `sync_from_window` | *Optional[int]* | :heavy_minus_sign: | Number of months of data to be fetched. Set this *or* `syncFromUTC`. | 24 | +| `sync_order` | *int* | :heavy_check_mark: | The sync in which data types are queued for a sync. | | | `sync_schedule` | *int* | :heavy_check_mark: | Number of hours after which this data type should be refreshed. | 24 | \ No newline at end of file diff --git a/platform/docs/models/shared/syncsettings.md b/platform/docs/models/shared/syncsettings.md index 931037bdc..531420226 100644 --- a/platform/docs/models/shared/syncsettings.md +++ b/platform/docs/models/shared/syncsettings.md @@ -1,10 +1,10 @@ -# SyncSettings - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -| `client_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for your client in Codat. | -| `overrides_defaults` | *Optional[bool]* | :heavy_minus_sign: | Set to `True` if you want to override the default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings). | +# SyncSettings + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `client_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for your client in Codat. | +| `overrides_defaults` | *Optional[bool]* | :heavy_minus_sign: | Set to `True` if you want to override the default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings). | | `settings` | List[[shared.SyncSetting](../../models/shared/syncsetting.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/updateconnectionstatus.md b/platform/docs/models/shared/updateconnectionstatus.md index d9d38733d..d5081c7c7 100644 --- a/platform/docs/models/shared/updateconnectionstatus.md +++ b/platform/docs/models/shared/updateconnectionstatus.md @@ -1,8 +1,9 @@ -# UpdateConnectionStatus - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +# UpdateConnectionStatus + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | | `status` | [Optional[shared.DataConnectionStatus]](../../models/shared/dataconnectionstatus.md) | :heavy_minus_sign: | The current authorization status of the data connection. | \ No newline at end of file diff --git a/platform/docs/models/shared/updateprofilesyncsettingsrequest.md b/platform/docs/models/shared/updateprofilesyncsettingsrequest.md new file mode 100644 index 000000000..a22716ad9 --- /dev/null +++ b/platform/docs/models/shared/updateprofilesyncsettingsrequest.md @@ -0,0 +1,10 @@ +# UpdateProfileSyncSettingsRequest + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `client_id` | *str* | :heavy_check_mark: | Unique identifier for your client in Codat. | +| `overrides_defaults` | *Optional[bool]* | :heavy_minus_sign: | Set to `True` if you want to override the default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings). | +| `settings` | List[[shared.SyncSetting](../../models/shared/syncsetting.md)] | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/validation.md b/platform/docs/models/shared/validation.md index 4cfc544dc..b208342e2 100644 --- a/platform/docs/models/shared/validation.md +++ b/platform/docs/models/shared/validation.md @@ -1,11 +1,11 @@ -# Validation - -A human-readable object describing validation decisions Codat has made when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here. - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -| `errors` | List[[shared.ValidationItem](../../models/shared/validationitem.md)] | :heavy_minus_sign: | N/A | +# Validation + +A human-readable object describing validation decisions Codat has made when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here. + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | +| `errors` | List[[shared.ValidationItem](../../models/shared/validationitem.md)] | :heavy_minus_sign: | N/A | | `warnings` | List[[shared.ValidationItem](../../models/shared/validationitem.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/validationitem.md b/platform/docs/models/shared/validationitem.md index 1aaf084c9..791ee2076 100644 --- a/platform/docs/models/shared/validationitem.md +++ b/platform/docs/models/shared/validationitem.md @@ -1,10 +1,11 @@ -# ValidationItem - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -| `item_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier for a validation item. | -| `message` | *OptionalNullable[str]* | :heavy_minus_sign: | A message outlining validation item's issue. | +# ValidationItem + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | +| `item_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier for a validation item. | +| `message` | *OptionalNullable[str]* | :heavy_minus_sign: | A message outlining validation item's issue. | | `validator_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of validator. | \ No newline at end of file diff --git a/platform/docs/models/shared/validationitem1.md b/platform/docs/models/shared/validationitem1.md index f1dd3252b..941d4deab 100644 --- a/platform/docs/models/shared/validationitem1.md +++ b/platform/docs/models/shared/validationitem1.md @@ -1,11 +1,11 @@ -# ValidationItem1 - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------- | -| `item_id` | *Optional[str]* | :heavy_minus_sign: | The unique identifier of the item that was validated. | -| `message` | *Optional[str]* | :heavy_minus_sign: | The message that describes the validation warning or error. | -| `rule_id` | *Optional[str]* | :heavy_minus_sign: | The unique identifier of the rule that wasn't met. | +# ValidationItem1 + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------- | +| `item_id` | *Optional[str]* | :heavy_minus_sign: | The unique identifier of the item that was validated. | +| `message` | *Optional[str]* | :heavy_minus_sign: | The message that describes the validation warning or error. | +| `rule_id` | *Optional[str]* | :heavy_minus_sign: | The unique identifier of the rule that wasn't met. | | `validator_name` | *Optional[str]* | :heavy_minus_sign: | The name of the validator that was used to validate the item. | \ No newline at end of file diff --git a/platform/docs/models/shared/validationresult.md b/platform/docs/models/shared/validationresult.md index c35b1edcd..cdccb1e31 100644 --- a/platform/docs/models/shared/validationresult.md +++ b/platform/docs/models/shared/validationresult.md @@ -1,9 +1,9 @@ -# ValidationResult - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | -| `errors` | List[[shared.ValidationItem1](../../models/shared/validationitem1.md)] | :heavy_minus_sign: | N/A | +# ValidationResult + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `errors` | List[[shared.ValidationItem1](../../models/shared/validationitem1.md)] | :heavy_minus_sign: | N/A | | `warnings` | List[[shared.ValidationItem1](../../models/shared/validationitem1.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/webhookconsumer.md b/platform/docs/models/shared/webhookconsumer.md index 27eb699e0..3be03744e 100644 --- a/platform/docs/models/shared/webhookconsumer.md +++ b/platform/docs/models/shared/webhookconsumer.md @@ -1,17 +1,17 @@ -# WebhookConsumer - -A webhook consumer is an HTTP endpoint that developers can configure to subscribe to Codat's supported event types. - -See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). - - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_tags` | List[*str*] | :heavy_minus_sign: | Company tags provide an additional way to filter messages, independent of event types. Company tags are case-sensitive, and only messages from companies with matching tags will be sent to this endpoint. Use the format `tagKey:tagValue`. | | -| `disabled` | *OptionalNullable[bool]* | :heavy_minus_sign: | Flag that enables or disables the endpoint from receiving events. Disabled when set to `true`. | | -| `event_types` | List[*str*] | :heavy_minus_sign: | An array of event types the webhook consumer subscribes to. | | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the webhook consumer. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# WebhookConsumer + +A webhook consumer is an HTTP endpoint that developers can configure to subscribe to Codat's supported event types. + +See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). + + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `company_tags` | List[*str*] | :heavy_minus_sign: | Company tags provide an additional way to filter messages, independent of event types. Company tags are case-sensitive, and only messages from companies with matching tags will be sent to this endpoint. Use the format `tagKey:tagValue`. | | +| `disabled` | *Optional[bool]* | :heavy_minus_sign: | Flag that enables or disables the endpoint from receiving events. Disabled when set to `true`. | | +| `event_types` | List[*str*] | :heavy_minus_sign: | An array of event types the webhook consumer subscribes to. | | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the webhook consumer. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `url` | *Optional[str]* | :heavy_minus_sign: | The URL that will consume webhook events dispatched by Codat. | | \ No newline at end of file diff --git a/platform/docs/models/shared/webhookconsumerprototype.md b/platform/docs/models/shared/webhookconsumerprototype.md index 18bfc6ca4..88b92e2d8 100644 --- a/platform/docs/models/shared/webhookconsumerprototype.md +++ b/platform/docs/models/shared/webhookconsumerprototype.md @@ -1,11 +1,11 @@ -# WebhookConsumerPrototype - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_tags` | List[*str*] | :heavy_minus_sign: | Company tags provide an additional way to filter messages, independent of event types. Company tags are case-sensitive, and only messages from companies with matching tags will be sent to this endpoint. Use the format `tagKey:tagValue`. | -| `disabled` | *OptionalNullable[bool]* | :heavy_minus_sign: | Flag that enables or disables the endpoint from receiving events. Disabled when set to `true`. | -| `event_types` | List[*str*] | :heavy_minus_sign: | An array of event types the webhook consumer subscribes to. | +# WebhookConsumerPrototype + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `company_tags` | List[*str*] | :heavy_minus_sign: | Company tags provide an additional way to filter messages, independent of event types. Company tags are case-sensitive, and only messages from companies with matching tags will be sent to this endpoint. Use the format `tagKey:tagValue`. | +| `disabled` | *Optional[bool]* | :heavy_minus_sign: | Flag that enables or disables the endpoint from receiving events. Disabled when set to `true`. | +| `event_types` | List[*str*] | :heavy_minus_sign: | An array of event types the webhook consumer subscribes to. | | `url` | *Optional[str]* | :heavy_minus_sign: | The URL that will consume webhook events dispatched by Codat. | \ No newline at end of file diff --git a/platform/docs/models/shared/webhookconsumers.md b/platform/docs/models/shared/webhookconsumers.md index 151edc9ec..8cd231374 100644 --- a/platform/docs/models/shared/webhookconsumers.md +++ b/platform/docs/models/shared/webhookconsumers.md @@ -1,8 +1,8 @@ -# WebhookConsumers - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +# WebhookConsumers + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | | `results` | List[[shared.WebhookConsumer](../../models/shared/webhookconsumer.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/platform/docs/models/shared/webhookzapierkey.md b/platform/docs/models/shared/webhookzapierkey.md new file mode 100644 index 000000000..5424b81a1 --- /dev/null +++ b/platform/docs/models/shared/webhookzapierkey.md @@ -0,0 +1,8 @@ +# WebhookZapierKey + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | +| `key` | *Optional[str]* | :heavy_minus_sign: | Integration key used to authorize Zapier's HTTP requests with Codat. | sk_integ_WM4dfoK1nKZnDE_kceze6hWDjbRwOZwG.us | \ No newline at end of file diff --git a/platform/docs/models/shared/writestatus.md b/platform/docs/models/shared/writestatus.md index c149e9143..51cebe6cf 100644 --- a/platform/docs/models/shared/writestatus.md +++ b/platform/docs/models/shared/writestatus.md @@ -1,21 +1,19 @@ -# WriteStatus - -The current status of the write request, which is the same as the push operation status. - -## Example Usage - -```python -from codat_platform.models.shared import WriteStatus - -value = WriteStatus.PENDING -``` - - -## Values - -| Name | Value | -| ----------- | ----------- | -| `PENDING` | Pending | -| `FAILED` | Failed | -| `SUCCESS` | Success | +# WriteStatus + +## Example Usage + +```python +from codat_platform.models.shared import WriteStatus + +value = WriteStatus.PENDING +``` + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `PENDING` | Pending | +| `FAILED` | Failed | +| `SUCCESS` | Success | | `TIMED_OUT` | TimedOut | \ No newline at end of file diff --git a/platform/docs/models/shared/writetype.md b/platform/docs/models/shared/writetype.md index 60a5e4f51..3943481e6 100644 --- a/platform/docs/models/shared/writetype.md +++ b/platform/docs/models/shared/writetype.md @@ -1,21 +1,21 @@ -# WriteType - -Type of write request. - -## Example Usage - -```python -from codat_platform.models.shared import WriteType - -value = WriteType.CREATE -``` - - -## Values - -| Name | Value | -| ------------------- | ------------------- | -| `CREATE` | Create | -| `UPDATE` | Update | -| `DELETE` | Delete | +# WriteType + +Type of write request. + +## Example Usage + +```python +from codat_platform.models.shared import WriteType + +value = WriteType.CREATE +``` + + +## Values + +| Name | Value | +| ------------------- | ------------------- | +| `CREATE` | Create | +| `UPDATE` | Update | +| `DELETE` | Delete | | `UPLOAD_ATTACHMENT` | UploadAttachment | \ No newline at end of file diff --git a/platform/docs/models/utils/retryconfig.md b/platform/docs/models/utils/retryconfig.md index 69dd549ec..0977111b8 100644 --- a/platform/docs/models/utils/retryconfig.md +++ b/platform/docs/models/utils/retryconfig.md @@ -1,24 +1,24 @@ -# RetryConfig - -Allows customizing the default retry configuration. Only usable with methods that mention they support retries. - -## Fields - -| Name | Type | Description | Example | -| ------------------------- | ----------------------------------- | --------------------------------------- | --------- | -| `strategy` | `*str*` | The retry strategy to use. | `backoff` | -| `backoff` | [BackoffStrategy](#backoffstrategy) | Configuration for the backoff strategy. | | -| `retry_connection_errors` | `*bool*` | Whether to retry on connection errors. | `true` | - -## BackoffStrategy - -The backoff strategy allows retrying a request with an exponential backoff between each retry. - -### Fields - -| Name | Type | Description | Example | -| ------------------ | --------- | ----------------------------------------- | -------- | -| `initial_interval` | `*int*` | The initial interval in milliseconds. | `500` | -| `max_interval` | `*int*` | The maximum interval in milliseconds. | `60000` | -| `exponent` | `*float*` | The exponent to use for the backoff. | `1.5` | +# RetryConfig + +Allows customizing the default retry configuration. Only usable with methods that mention they support retries. + +## Fields + +| Name | Type | Description | Example | +| ------------------------- | ----------------------------------- | --------------------------------------- | --------- | +| `strategy` | `*str*` | The retry strategy to use. | `backoff` | +| `backoff` | [BackoffStrategy](#backoffstrategy) | Configuration for the backoff strategy. | | +| `retry_connection_errors` | `*bool*` | Whether to retry on connection errors. | `true` | + +## BackoffStrategy + +The backoff strategy allows retrying a request with an exponential backoff between each retry. + +### Fields + +| Name | Type | Description | Example | +| ------------------ | --------- | ----------------------------------------- | -------- | +| `initial_interval` | `*int*` | The initial interval in milliseconds. | `500` | +| `max_interval` | `*int*` | The maximum interval in milliseconds. | `60000` | +| `exponent` | `*float*` | The exponent to use for the backoff. | `1.5` | | `max_elapsed_time` | `*int*` | The maximum elapsed time in milliseconds. | `300000` | \ No newline at end of file diff --git a/platform/docs/sdks/companies/README.md b/platform/docs/sdks/companies/README.md index 5d1154a7d..e26c9d924 100644 --- a/platform/docs/sdks/companies/README.md +++ b/platform/docs/sdks/companies/README.md @@ -1,871 +1,846 @@ -# Companies - -## Overview - -Create and manage your SMB users' companies. - -### Available Operations - -* [add_product](#add_product) - Add product -* [create](#create) - Create company -* [delete](#delete) - Delete a company -* [get](#get) - Get company -* [get_access_token](#get_access_token) - Get company access token -* [get_company_sync_settings](#get_company_sync_settings) - Get company sync settings -* [list](#list) - List companies -* [refresh_product_data](#refresh_product_data) - Refresh product data -* [remove_product](#remove_product) - Remove product -* [replace](#replace) - Replace company -* [set_company_sync_settings](#set_company_sync_settings) - Set company sync settings -* [update](#update) - Update company - -## add_product - -Use the *Add product* endpoint to enable a product for the company specified by `companyId`. - -> Note: This feature is currently in alpha and available only to participants in the development program. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.companies.add_product(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "product_identifier": "bank-feeds", - }) - - # Use the SDK ... - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `request` | [operations.AddProductRequest](../../models/operations/addproductrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## create - -Use the *Create company* endpoint to create a new [company](https://docs.codat.io/platform-api#/schemas/Company) that represents your customer in Codat. - -A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - -If forbidden characters (see `name` pattern) are present in the request, a company will be created with the forbidden characters removed. For example, `Company (Codat[1])` with be created as `Company Codat1`. - -### Example Usage: Malformed query - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.create(request={ - "description": "Requested early access to the new financing scheme.", - "name": "Bank of Dave", - }) - - # Handle response - print(res) - -``` -### Example Usage: With a description - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.create(request={ - "description": "Technology services, including web and app design and development", - "name": "Technicalium", - }) - - # Handle response - print(res) - -``` -### Example Usage: With a tag - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.create(request={ - "description": "Requested early access to the new financing scheme.", - "name": "Bank of Dave", - }) - - # Handle response - print(res) - -``` -### Example Usage: With no description - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.create(request={ - "name": "Technicalium", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | -| `request` | [shared.CompanyRequestBody](../../models/shared/companyrequestbody.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Company](../../models/shared/company.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## delete - -The *Delete company* endpoint permanently deletes a [company](https://docs.codat.io/platform-api#/schemas/Company), its [connections](https://docs.codat.io/platform-api#/schemas/Connection) and any cached data. This operation is irreversible. - -A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.companies.delete(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Use the SDK ... - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `request` | [operations.DeleteCompanyRequest](../../models/operations/deletecompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get - -The *Get company* endpoint returns a single company for a given `companyId`. - -A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - -### Example Usage: Parent multi-entity company - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Simple company - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Subsidiary multi-entity company - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `request` | [operations.GetCompanyRequest](../../models/operations/getcompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Company](../../models/shared/company.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get_access_token - -Use the _Get company access token_ endpoint to return an access token for the specified company ID. The token is valid for one day. - -The token is required by Codat's embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to verify the identity of the user and improve the reliability of data provided by them. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.get_access_token(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `request` | [operations.GetCompanyAccessTokenRequest](../../models/operations/getcompanyaccesstokenrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.CompanyAccessToken](../../models/shared/companyaccesstoken.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get_company_sync_settings - -Retrieve the [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings) for a specific company. This includes how often data types should be queued to be updated, and how much history should be fetched. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.get_company_sync_settings(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | -| `request` | [operations.GetCompanySyncSettingsRequest](../../models/operations/getcompanysyncsettingsrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.CompanySyncSettings](../../models/shared/companysyncsettings.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## list - -The *List companies* endpoint returns a list of [companies](https://docs.codat.io/platform-api#/schemas/Company) associated to your instances. - -A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - -## Filter by tags - -The *List companies* endpoint supports the filtering of companies using [tags](https://docs.codat.io/using-the-api/managing-companies#add-metadata-to-a-company). It supports the following operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying): - -- equals (`=`) -- not equals (`!=`) -- contains (`~`) - -For example, you can use the querying to filter companies tagged with a specific foreign key, region, or owning team: -- Foreign key: `uid = {yourCustomerId}` -- Region: `region != uk` -- Owning team and region: `region = uk && owningTeam = invoice-finance` - -### Example Usage: List of Companies - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.list(request={ - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - "tags": "region=uk && team=invoice-finance", - }) - - # Handle response - print(res) - -``` -### Example Usage: One company - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.list(request={ - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - "tags": "region=uk && team=invoice-finance", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `request` | [operations.ListCompaniesRequest](../../models/operations/listcompaniesrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Companies](../../models/shared/companies.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## refresh_product_data - -Use the **Refresh product data** endpoint to manually refresh data for a custom product for a specific company. - -### Tips and traps - -- This endpoint only supports refreshing data for **custom products** and can't be used for Codat's standard solutions. Refer to [individual solutions' documentation](https://docs.codat.io/) instead. -- If a data sync is already in progress for a custom product, the refresh request will return a `Bad request (400)` response. -- If a company has multiple custom products enabled, you can refresh data for each product individually. - - Optionally include a request body with `dataTypes` to refresh only selected data types for the specified product. If omitted, the product's scheduled refresh is triggered as usual. - - When specifying `dataTypes`, each value must be a valid data type supported by the product. Invalid values will result in a `Bad request (400)` response listing valid options. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.companies.refresh_product_data(request={ - "request_body": { - "data_types": [ - "invoices", - "payments", - ], - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "product_identifier": "bank-feeds", - }) - - # Use the SDK ... - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -| `request` | [operations.RefreshProductDataRequest](../../models/operations/refreshproductdatarequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## remove_product - -Use the *Remove product* endpoint to disable a product for the company specified by `companyId`. - -> Note: This feature is currently in alpha and available only to participants in the development program. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.companies.remove_product(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "product_identifier": "bank-feeds", - }) - - # Use the SDK ... - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `request` | [operations.RemoveProductRequest](../../models/operations/removeproductrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## replace - -Use the *Replace company* endpoint to replace the existing name, description, and tags of the company. Calling the endpoint will replace existing values even if new values haven't been defined in the payload. - -A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - -### Example Usage: Unauthorized - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.replace(request={ - "company_request_body": { - "description": "Requested early access to the new financing scheme.", - "name": "Bank of Dave", - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Update description - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.replace(request={ - "company_request_body": { - "description": "Additional documents required", - "name": "Same name", - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Update name - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.replace(request={ - "company_request_body": { - "name": "New Name", - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `request` | [operations.ReplaceCompanyRequest](../../models/operations/replacecompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Company](../../models/shared/company.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## set_company_sync_settings - -Set the sync settings for a specific company. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.companies.set_company_sync_settings(request={ - "request_body": { - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "settings": [ - { - "data_type": shared.DataType.INVOICES, - "fetch_on_first_link": True, - "is_locked": True, - "months_to_sync": 24, - "sync_from_utc": "2020-01-01T12:00:00.000Z", - "sync_from_window": 24, - "sync_order": 0, - "sync_schedule": 24, - }, - ], - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Use the SDK ... - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | -| `request` | [operations.SetCompanySyncSettingsRequest](../../models/operations/setcompanysyncsettingsrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## update - -Use the *Update company* endpoint to update the name, description, or tags of the company. - -The *Update company* endpoint doesn't have any required fields. If any of the fields provided are `null` or not provided, they won't be included in the update. - -A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. - -### Example Usage: Unauthorized - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.update(request={ - "company_update_request": { - "description": "Requested early access to the new financing scheme.", - "name": "Bank of Dave", - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Update name - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.update(request={ - "company_update_request": { - "name": "New Name", - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Update tags - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.companies.update(request={ - "company_update_request": { - "tags": { - "refrence": "new reference", - }, - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `request` | [operations.UpdateCompanyRequest](../../models/operations/updatecompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Company](../../models/shared/company.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Companies + +## Overview + +Create and manage your SMB users' companies. + +### Available Operations + +* [add_product](#add_product) - Add product +* [create](#create) - Create company +* [delete](#delete) - Delete a company +* [get](#get) - Get company +* [get_access_token](#get_access_token) - Get company access token +* [get_company_sync_settings](#get_company_sync_settings) - Get company sync settings +* [list](#list) - List companies +* [refresh_product_data](#refresh_product_data) - Refresh product data +* [remove_product](#remove_product) - Remove product +* [replace](#replace) - Replace company +* [set_company_sync_settings](#set_company_sync_settings) - Set company sync settings +* [update](#update) - Update company + +## add_product + +Use the *Add product* endpoint to enable a product for the company specified by `companyId`. + +> Note: This feature is currently in alpha and available only to participants in the development program. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.companies.add_product(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "product_identifier": "bank-feeds", + }) + + # Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `request` | [operations.AddProductRequest](../../models/operations/addproductrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## create + +Use the *Create company* endpoint to create a new [company](https://docs.codat.io/platform-api#/schemas/Company) that represents your customer in Codat. + +A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. + +If forbidden characters (see `name` pattern) are present in the request, a company will be created with the forbidden characters removed. For example, `Company (Codat[1])` with be created as `Company Codat1`. + +### Example Usage: Malformed query + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.create(request={ + "description": "Requested early access to the new financing scheme.", + "name": "Bank of Dave", + }) + + # Handle response + print(res) + +``` +### Example Usage: With a description + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.create(request={ + "description": "Technology services, including web and app design and development", + "name": "Technicalium", + }) + + # Handle response + print(res) + +``` +### Example Usage: With a tag + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.create(request={ + "description": "Requested early access to the new financing scheme.", + "name": "Bank of Dave", + }) + + # Handle response + print(res) + +``` +### Example Usage: With no description + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.create(request={ + "name": "Technicalium", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `request` | [shared.CompanyRequestBody](../../models/shared/companyrequestbody.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Company](../../models/shared/company.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## delete + +The *Delete company* endpoint permanently deletes a [company](https://docs.codat.io/platform-api#/schemas/Company), its [connections](https://docs.codat.io/platform-api#/schemas/Connection) and any cached data. This operation is irreversible. + +A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. + + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.companies.delete(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `request` | [operations.DeleteCompanyRequest](../../models/operations/deletecompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get + +The *Get company* endpoint returns a single company for a given `companyId`. + +A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. + + +### Example Usage: Parent multi-entity company + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Simple company + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Subsidiary multi-entity company + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `request` | [operations.GetCompanyRequest](../../models/operations/getcompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Company](../../models/shared/company.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get_access_token + +Use the _Get company access token_ endpoint to return an access token for the specified company ID. The token is valid for one day. + +The token is required by Codat's embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to verify the identity of the user and improve the reliability of data provided by them. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.get_access_token(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `request` | [operations.GetCompanyAccessTokenRequest](../../models/operations/getcompanyaccesstokenrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.CompanyAccessToken](../../models/shared/companyaccesstoken.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get_company_sync_settings + +Retrieve the [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings) for a specific company. This includes how often data types should be queued to be updated, and how much history should be fetched. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.get_company_sync_settings(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `request` | [operations.GetCompanySyncSettingsRequest](../../models/operations/getcompanysyncsettingsrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.CompanySyncSettings](../../models/shared/companysyncsettings.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## list + +The *List companies* endpoint returns a list of [companies](https://docs.codat.io/platform-api#/schemas/Company) associated to your instances. + +A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. + +## Filter by tags + +The *List companies* endpoint supports the filtering of companies using [tags](https://docs.codat.io/using-the-api/managing-companies#add-metadata-to-a-company). It supports the following operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying): + +- equals (`=`) +- not equals (`!=`) +- contains (`~`) + +For example, you can use the querying to filter companies tagged with a specific foreign key, region, or owning team: +- Foreign key: `uid = {yourCustomerId}` +- Region: `region != uk` +- Owning team and region: `region = uk && owningTeam = invoice-finance` + +### Example Usage: List of Companies + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.list(request={ + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + "tags": "region=uk && team=invoice-finance", + }) + + # Handle response + print(res) + +``` +### Example Usage: One company + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.list(request={ + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + "tags": "region=uk && team=invoice-finance", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `request` | [operations.ListCompaniesRequest](../../models/operations/listcompaniesrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Companies](../../models/shared/companies.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## refresh_product_data + +Use the **Refresh product data** endpoint to manually refresh data for a custom product for a specific company. + +### Tips and traps + +- This endpoint only supports refreshing data for **custom products** and can't be used for Codat's standard solutions. Refer to [individual solutions' documentation](https://docs.codat.io/) instead. +- If a data sync is already in progress for a custom product, the refresh request will return a `Bad request (400)` response. +- If a company has multiple custom products enabled, you can refresh data for each product individually. + - Optionally include a request body with `dataTypes` to refresh only selected data types for the specified product. If omitted, the product's scheduled refresh is triggered as usual. + - When specifying `dataTypes`, each value must be a valid data type supported by the product. Invalid values will result in a `Bad request (400)` response listing valid options. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.companies.refresh_product_data(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "product_identifier": "bank-feeds", + }) + + # Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| `request` | [operations.RefreshProductDataRequest](../../models/operations/refreshproductdatarequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## remove_product + +Use the *Remove product* endpoint to disable a product for the company specified by `companyId`. + +> Note: This feature is currently in alpha and available only to participants in the development program. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.companies.remove_product(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "product_identifier": "bank-feeds", + }) + + # Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `request` | [operations.RemoveProductRequest](../../models/operations/removeproductrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## replace + +Use the *Replace company* endpoint to replace the existing name, description, and tags of the company. Calling the endpoint will replace existing values even if new values haven't been defined in the payload. + +A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. + +### Example Usage: Unauthorized + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.replace(request={ + "company_request_body": { + "description": "Requested early access to the new financing scheme.", + "name": "Bank of Dave", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Update description + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.replace(request={ + "company_request_body": { + "description": "Additional documents required", + "name": "Same name", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Update name + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.replace(request={ + "company_request_body": { + "name": "New Name", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `request` | [operations.ReplaceCompanyRequest](../../models/operations/replacecompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Company](../../models/shared/company.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## set_company_sync_settings + +Set the sync settings for a specific company. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.companies.set_company_sync_settings(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `request` | [operations.SetCompanySyncSettingsRequest](../../models/operations/setcompanysyncsettingsrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## update + +Use the *Update company* endpoint to update the name, description, or tags of the company. + +The *Update company* endpoint doesn't have any required fields. If any of the fields provided are `null` or not provided, they won't be included in the update. + +A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. + +### Example Usage: Unauthorized + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.update(request={ + "company_update_request": { + "description": "Requested early access to the new financing scheme.", + "name": "Bank of Dave", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Update name + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.update(request={ + "company_update_request": { + "name": "New Name", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Update tags + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.companies.update(request={ + "company_update_request": {}, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `request` | [operations.UpdateCompanyRequest](../../models/operations/updatecompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Company](../../models/shared/company.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/platform/docs/sdks/connectionmanagement/README.md b/platform/docs/sdks/connectionmanagement/README.md index edf3ae3a9..9b0c2ba55 100644 --- a/platform/docs/sdks/connectionmanagement/README.md +++ b/platform/docs/sdks/connectionmanagement/README.md @@ -1,63 +1,63 @@ -# ~~ConnectionManagement~~ - -> [!WARNING] -> This SDK is **DEPRECATED** - -## Overview - -Configure UI and retrieve access tokens for authentication used by **Connections SDK**. - -### Available Operations - -* [~~get~~](#get) - Get access token (old) :warning: **Deprecated** Use [get_access_token](docs/sdks/companies/README.md#get_access_token) instead. - -## ~~get~~ - -The new [Get company access token](https://docs.codat.io/platform-api#/operations/get-company-access-token) endpoint replaces this endpoint and includes additional functionality. - -> :warning: **DEPRECATED**: The endpoint for generating company-specific connection management access tokens has been deprecated. -Codat now supports a global company access token, providing seamless access across multiple products. -Update your integration to use the global token for improved efficiency and consistency. -. Use `get_access_token` instead. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.connection_management.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -| `request` | [operations.GetConnectionManagementAccessTokenRequest](../../models/operations/getconnectionmanagementaccesstokenrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.ConnectionManagementAccessToken](../../models/shared/connectionmanagementaccesstoken.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# ~~ConnectionManagement~~ + +> [!WARNING] +> This SDK is **DEPRECATED** + +## Overview + +Configure UI and retrieve access tokens for authentication used by **Connections SDK**. + +### Available Operations + +* [~~get~~](#get) - Get access token (old) :warning: **Deprecated** Use [get_access_token](docs/sdks/companies/README.md#get_access_token) instead. + +## ~~get~~ + +The new [Get company access token](https://docs.codat.io/platform-api#/operations/get-company-access-token) endpoint replaces this endpoint and includes additional functionality. + +> :warning: **DEPRECATED**: The endpoint for generating company-specific connection management access tokens has been deprecated. +Codat now supports a global company access token, providing seamless access across multiple products. +Update your integration to use the global token for improved efficiency and consistency. +. Use `get_access_token` instead. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.connection_management.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| `request` | [operations.GetConnectionManagementAccessTokenRequest](../../models/operations/getconnectionmanagementaccesstokenrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.ConnectionManagementAccessToken](../../models/shared/connectionmanagementaccesstoken.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/platform/docs/sdks/connections/README.md b/platform/docs/sdks/connections/README.md index 1128a1f23..93ff407a0 100644 --- a/platform/docs/sdks/connections/README.md +++ b/platform/docs/sdks/connections/README.md @@ -1,325 +1,319 @@ -# Connections - -## Overview - -Create new and manage existing data connections for a company. - -### Available Operations - -* [create](#create) - Create connection -* [delete](#delete) - Delete connection -* [get](#get) - Get connection -* [list](#list) - List connections -* [unlink](#unlink) - Unlink connection -* [update_authorization](#update_authorization) - Update authorization - -## create - -Creates a connection for the company by providing a valid `platformKey`. - -Use the [List Integrations](https://docs.codat.io/platform-api#/operations/list-integrations) endpoint to access valid platform keys. - -### Example Usage: Connection - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.connections.create(request={ - "request_body": { - "platform_key": "gbol", - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Unauthorized - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.connections.create(request={ - "request_body": { - "platform_key": "gbol", - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `request` | [operations.CreateConnectionRequest](../../models/operations/createconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Connection](../../models/shared/connection.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## delete - -Revoke and remove a connection from a company. -This operation is not reversible. The end user would need to reauthorize a new data connection if you wish to view new data for this company. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.connections.delete(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Use the SDK ... - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `request` | [operations.DeleteConnectionRequest](../../models/operations/deleteconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get - -Returns a specific connection for a company when valid identifiers are provided. If the identifiers are for a deleted company and/or connection, a not found response is returned. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.connections.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `request` | [operations.GetConnectionRequest](../../models/operations/getconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Connection](../../models/shared/connection.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## list - -List the connections for a company. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.connections.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -| `request` | [operations.ListConnectionsRequest](../../models/operations/listconnectionsrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Connections](../../models/shared/connections.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## unlink - -This allows you to deauthorize a connection, without deleting it from Codat. This means you can still view any data that has previously been pulled into Codat, and also lets you re-authorize in future if your customer wishes to resume sharing their data. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.connections.unlink(request={ - "update_connection_status": { - "status": shared.DataConnectionStatus.UNLINKED, - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `request` | [operations.UnlinkConnectionRequest](../../models/operations/unlinkconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Connection](../../models/shared/connection.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## update_authorization - -Update data connection's authorization. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.connections.update_authorization(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | -| `request` | [operations.UpdateConnectionAuthorizationRequest](../../models/operations/updateconnectionauthorizationrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Connection](../../models/shared/connection.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Connections + +## Overview + +Create new and manage existing data connections for a company. + +### Available Operations + +* [create](#create) - Create connection +* [delete](#delete) - Delete connection +* [get](#get) - Get connection +* [list](#list) - List connections +* [unlink](#unlink) - Unlink connection +* [update_authorization](#update_authorization) - Update authorization + +## create + +Creates a connection for the company by providing a valid `platformKey`. + +Use the [List Integrations](https://docs.codat.io/platform-api#/operations/list-integrations) endpoint to access valid platform keys. + +### Example Usage: Connection + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.connections.create(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Unauthorized + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.connections.create(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `request` | [operations.CreateConnectionRequest](../../models/operations/createconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Connection](../../models/shared/connection.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## delete + +Revoke and remove a connection from a company. +This operation is not reversible. The end user would need to reauthorize a new data connection if you wish to view new data for this company. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.connections.delete(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `request` | [operations.DeleteConnectionRequest](../../models/operations/deleteconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get + +Returns a specific connection for a company when valid identifiers are provided. If the identifiers are for a deleted company and/or connection, a not found response is returned. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.connections.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `request` | [operations.GetConnectionRequest](../../models/operations/getconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Connection](../../models/shared/connection.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## list + +List the connections for a company. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.connections.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `request` | [operations.ListConnectionsRequest](../../models/operations/listconnectionsrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Connections](../../models/shared/connections.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## unlink + +This allows you to deauthorize a connection, without deleting it from Codat. This means you can still view any data that has previously been pulled into Codat, and also lets you re-authorize in future if your customer wishes to resume sharing their data. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.connections.unlink(request={ + "update_connection_status": { + "status": shared.DataConnectionStatus.UNLINKED, + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `request` | [operations.UnlinkConnectionRequest](../../models/operations/unlinkconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Connection](../../models/shared/connection.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## update_authorization + +Update data connection's authorization. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.connections.update_authorization(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | +| `request` | [operations.UpdateConnectionAuthorizationRequest](../../models/operations/updateconnectionauthorizationrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Connection](../../models/shared/connection.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/platform/docs/sdks/cors/README.md b/platform/docs/sdks/cors/README.md index 02c516444..b6b7a1a94 100644 --- a/platform/docs/sdks/cors/README.md +++ b/platform/docs/sdks/cors/README.md @@ -1,138 +1,138 @@ -# ~~Cors~~ - -> [!WARNING] -> This SDK is **DEPRECATED** - -## Overview - -### Available Operations - -* [~~get~~](#get) - Get CORS settings (old) :warning: **Deprecated** Use [get](docs/sdks/settings/README.md#get) instead. -* [~~set~~](#set) - Set CORS settings (old) :warning: **Deprecated** Use [set](docs/sdks/settings/README.md#set) instead. - -## ~~get~~ - -The *Get CORS settings* endpoint returns the allowed origins (i.e. your domains) you want to allow cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)) with Codat. - -Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. - -> :warning: **DEPRECATED**: The new [Get CORS settings](https://docs.codat.io/platform-api#/operations/get-cors-settings) endpoint replaces this endpoint and includes additional functionality. -Update your integrations to use the new path `/corsSettings` as the existing route will be removed in a future release. -. Use `get` instead. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.cors.get() - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.ConnectionManagementAllowedOrigins](../../models/shared/connectionmanagementallowedorigins.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## ~~set~~ - -The *Set CORS settings* endpoint allows you to register allowed origins (i.e. your domains) for use in cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)). - -Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. - -> :warning: **DEPRECATED**: The new [Set CORS settings](https://docs.codat.io/platform-api#/operations/set-cors-settings) endpoint replaces this endpoint and includes additional functionality. -Update your integrations to use the new path `/corsSettings` as the existing route will be removed in a future release. -. Use `set` instead. - -### Example Usage: Allowed origins - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.cors.set(request={ - "allowed_origins": [ - "https://www.bank-of-dave.com", - ], - }) - - # Handle response - print(res) - -``` -### Example Usage: Unauthorized - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.cors.set(request={ - "allowed_origins": [ - "https://www.bank-of-dave.com", - ], - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | -| `request` | [shared.ConnectionManagementAllowedOrigins](../../models/shared/connectionmanagementallowedorigins.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.ConnectionManagementAllowedOrigins](../../models/shared/connectionmanagementallowedorigins.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# ~~Cors~~ + +> [!WARNING] +> This SDK is **DEPRECATED** + +## Overview + +### Available Operations + +* [~~get~~](#get) - Get CORS settings (old) :warning: **Deprecated** Use [get](docs/sdks/settings/README.md#get) instead. +* [~~set~~](#set) - Set CORS settings (old) :warning: **Deprecated** Use [set](docs/sdks/settings/README.md#set) instead. + +## ~~get~~ + +The *Get CORS settings* endpoint returns the allowed origins (i.e. your domains) you want to allow cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)) with Codat. + +Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. + +> :warning: **DEPRECATED**: The new [Get CORS settings](https://docs.codat.io/platform-api#/operations/get-cors-settings) endpoint replaces this endpoint and includes additional functionality. +Update your integrations to use the new path `/corsSettings` as the existing route will be removed in a future release. +. Use `get` instead. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.cors.get() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.ConnectionManagementAllowedOrigins](../../models/shared/connectionmanagementallowedorigins.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## ~~set~~ + +The *Set CORS settings* endpoint allows you to register allowed origins (i.e. your domains) for use in cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)). + +Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. + +> :warning: **DEPRECATED**: The new [Set CORS settings](https://docs.codat.io/platform-api#/operations/set-cors-settings) endpoint replaces this endpoint and includes additional functionality. +Update your integrations to use the new path `/corsSettings` as the existing route will be removed in a future release. +. Use `set` instead. + +### Example Usage: Allowed origins + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.cors.set(request={ + "allowed_origins": [ + "https://www.bank-of-dave.com", + ], + }) + + # Handle response + print(res) + +``` +### Example Usage: Unauthorized + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.cors.set(request={ + "allowed_origins": [ + "https://www.bank-of-dave.com", + ], + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `request` | [shared.ConnectionManagementAllowedOrigins](../../models/shared/connectionmanagementallowedorigins.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.ConnectionManagementAllowedOrigins](../../models/shared/connectionmanagementallowedorigins.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/platform/docs/sdks/customdatatype/README.md b/platform/docs/sdks/customdatatype/README.md index 0726b4f7b..daf2197d0 100644 --- a/platform/docs/sdks/customdatatype/README.md +++ b/platform/docs/sdks/customdatatype/README.md @@ -1,384 +1,350 @@ -# CustomDataType - -## Overview - -Configure and pull additional data types that are not included in Codat's standardized data model. - -### Available Operations - -* [configure](#configure) - Configure custom data type -* [get_configuration](#get_configuration) - Get custom data configuration -* [list](#list) - List custom data type records -* [refresh](#refresh) - Refresh custom data type - -## configure - -The *Configure custom data type* endpoint allows you to maintain or change the configuration required to return a custom data type for a specific integration. - -A [custom data type](https://docs.codat.io/using-the-api/custom-data) is an additional data type you can create that is not included in Codat's standardized data model. - -### Tips and traps - -- You can only configure a single custom data type for a single platform at a time. Use the endpoint multiple times if you need to configure it for multiple platforms. - -- You can only indicate a single data source for each customer data type. - -- Make your custom configuration as similar as possible to our standard data types so you can interact with them in exactly the same way. - -### Example Usage: Dynamics 365 Business Central - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.custom_data_type.configure(request={ - "custom_data_type_configuration": { - "data_source": "api/purchaseOrders", - "key_by": [ - "$[*].id", - ], - "required_data": { - "currency": "$[*].currencyCode", - "number": "$[*].number", - "date": "$[*].orderDate", - "totalexvat": "$[*].totalAmountExcludingTax", - "totaltax": "$[*].totalTaxAmount", - "vendor": "$[*].number", - }, - "source_modified_date": [ - "$[*].lastModifiedDateTime", - ], - }, - "custom_data_identifier": "DynamicsPurchaseOrders", - "platform_key": "gbol", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Online - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.custom_data_type.configure(request={ - "custom_data_type_configuration": { - "data_source": "/query?query=select * from Account", - "key_by": [ - "$.Id", - ], - "required_data": { - "id": "$.Id", - "Currentbal": "$.CurrentBalance", - "SubAcc": "$.SubAccount", - }, - "source_modified_date": [ - "$.time", - ], - }, - "custom_data_identifier": "DynamicsPurchaseOrders", - "platform_key": "gbol", - }) - - # Handle response - print(res) - -``` -### Example Usage: Unauthorized - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.custom_data_type.configure(request={ - "custom_data_type_configuration": { - "data_source": "api/purchaseOrders?$filter=currencyCode eq 'NOK'", - "key_by": [ - "$[*].id", - ], - "required_data": { - "currencyCode": "$[*].currencyCode", - "id": "$[*].id", - "number": "$[*].number", - "orderDate": "$[*].orderDate", - "totalAmountExcludingTax": "$[*].totalAmountExcludingTax", - "totalTaxAmount": "$[*].totalTaxAmount", - "vendorName": "$[*].number", - }, - "source_modified_date": [ - "$[*].lastModifiedDateTime", - ], - }, - "custom_data_identifier": "DynamicsPurchaseOrders", - "platform_key": "gbol", - }) - - # Handle response - print(res) - -``` -### Example Usage: Xero Mapping Arrays - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.custom_data_type.configure(request={ - "custom_data_type_configuration": { - "data_source": "/api.xro/2.0/Invoices", - "key_by": [ - "$.InvoiceID", - ], - "required_data": { - "invNumber": "$.InvoiceNumber", - "type": "$.Type", - "InvoiceID": "$.InvoiceID", - "lines": "$.LineItems[*]", - }, - "source_modified_date": [ - "$.UpdatedDateUTC", - ], - }, - "custom_data_identifier": "DynamicsPurchaseOrders", - "platform_key": "gbol", - }) - - # Handle response - print(res) - -``` -### Example Usage: Xero Simple Record - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.custom_data_type.configure(request={ - "custom_data_type_configuration": { - "data_source": "/api.xro/2.0/Accounts", - "key_by": [ - "$.AccountID", - ], - "required_data": { - "code": "$.Code", - "accountId": "$.AccountID", - "type": "$.Type", - "SysAcc": "$.SystemAccount", - }, - }, - "custom_data_identifier": "DynamicsPurchaseOrders", - "platform_key": "gbol", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | -| `request` | [operations.ConfigureCustomDataTypeRequest](../../models/operations/configurecustomdatatyperequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.CustomDataTypeConfiguration](../../models/shared/customdatatypeconfiguration.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get_configuration - -The *Get custom data configuration* endpoint returns existing configuration details for the specified custom data type and integration pair you previously configured. - -A [custom data type](https://docs.codat.io/using-the-api/custom-data) is an additional data type you can create that is not included in Codat's standardized data model. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.custom_data_type.get_configuration(request={ - "custom_data_identifier": "DynamicsPurchaseOrders", - "platform_key": "gbol", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -| `request` | [operations.GetCustomDataTypeConfigurationRequest](../../models/operations/getcustomdatatypeconfigurationrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.CustomDataTypeRecords](../../models/shared/customdatatyperecords.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## list - -The *List custom data type records* endpoint returns a paginated list of records pulled for the specified custom data type you previously configured. - -A [custom data type](https://docs.codat.io/using-the-api/custom-data) is an additional data type you can create that is not included in Codat's standardized data model.s endpoint returns a paginated list of records whose schema is defined [Configure custom data type](https://docs.codat.io/platform-api#/operations/configure-custom-data-type) - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.custom_data_type.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "custom_data_identifier": "DynamicsPurchaseOrders", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `request` | [operations.ListCustomDataTypeRecordsRequest](../../models/operations/listcustomdatatyperecordsrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.CustomDataTypeRecords](../../models/shared/customdatatyperecords.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| --------------------------------- | --------------------------------- | --------------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429, 451 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## refresh - -The *Refresh custom data type* endpoint refreshes the specified custom data type for a given company. This is an asynchronous operation that will sync updated data from the linked integration into Codat for you to view. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.custom_data_type.refresh(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "custom_data_identifier": "DynamicsPurchaseOrders", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `request` | [operations.RefreshCustomDataTypeRequest](../../models/operations/refreshcustomdatatyperequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.PullOperation](../../models/shared/pulloperation.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429, 451 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# CustomDataType + +## Overview + +Configure and pull additional data types that are not included in Codat's standardized data model. + +### Available Operations + +* [configure](#configure) - Configure custom data type +* [get_configuration](#get_configuration) - Get custom data configuration +* [list](#list) - List custom data type records +* [refresh](#refresh) - Refresh custom data type + +## configure + +The *Configure custom data type* endpoint allows you to maintain or change the configuration required to return a custom data type for a specific integration. + +A [custom data type](https://docs.codat.io/using-the-api/custom-data) is an additional data type you can create that is not included in Codat's standardized data model. + +### Tips and traps + +- You can only configure a single custom data type for a single platform at a time. Use the endpoint multiple times if you need to configure it for multiple platforms. + +- You can only indicate a single data source for each customer data type. + +- Make your custom configuration as similar as possible to our standard data types so you can interact with them in exactly the same way. + +### Example Usage: Dynamics 365 Business Central + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.custom_data_type.configure(request={ + "custom_data_type_configuration": { + "data_source": "api/purchaseOrders", + "key_by": [ + "$[*].id", + ], + "source_modified_date": [ + "$[*].lastModifiedDateTime", + ], + }, + "custom_data_identifier": "DynamicsPurchaseOrders", + "platform_key": "gbol", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Online + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.custom_data_type.configure(request={ + "custom_data_type_configuration": { + "data_source": "/query?query=select * from Account", + "key_by": [ + "$.Id", + ], + "source_modified_date": [ + "$.time", + ], + }, + "custom_data_identifier": "DynamicsPurchaseOrders", + "platform_key": "gbol", + }) + + # Handle response + print(res) + +``` +### Example Usage: Unauthorized + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.custom_data_type.configure(request={ + "custom_data_type_configuration": { + "data_source": "api/purchaseOrders?$filter=currencyCode eq 'NOK'", + "key_by": [ + "$[*].id", + ], + "source_modified_date": [ + "$[*].lastModifiedDateTime", + ], + }, + "custom_data_identifier": "DynamicsPurchaseOrders", + "platform_key": "gbol", + }) + + # Handle response + print(res) + +``` +### Example Usage: Xero Mapping Arrays + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.custom_data_type.configure(request={ + "custom_data_type_configuration": { + "data_source": "/api.xro/2.0/Invoices", + "key_by": [ + "$.InvoiceID", + ], + "source_modified_date": [ + "$.UpdatedDateUTC", + ], + }, + "custom_data_identifier": "DynamicsPurchaseOrders", + "platform_key": "gbol", + }) + + # Handle response + print(res) + +``` +### Example Usage: Xero Simple Record + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.custom_data_type.configure(request={ + "custom_data_type_configuration": { + "data_source": "/api.xro/2.0/Accounts", + "key_by": [ + "$.AccountID", + ], + }, + "custom_data_identifier": "DynamicsPurchaseOrders", + "platform_key": "gbol", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `request` | [operations.ConfigureCustomDataTypeRequest](../../models/operations/configurecustomdatatyperequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.CustomDataTypeConfiguration](../../models/shared/customdatatypeconfiguration.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get_configuration + +The *Get custom data configuration* endpoint returns existing configuration details for the specified custom data type and integration pair you previously configured. + +A [custom data type](https://docs.codat.io/using-the-api/custom-data) is an additional data type you can create that is not included in Codat's standardized data model. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.custom_data_type.get_configuration(request={ + "custom_data_identifier": "DynamicsPurchaseOrders", + "platform_key": "gbol", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | +| `request` | [operations.GetCustomDataTypeConfigurationRequest](../../models/operations/getcustomdatatypeconfigurationrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.CustomDataTypeRecords](../../models/shared/customdatatyperecords.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## list + +The *List custom data type records* endpoint returns a paginated list of records pulled for the specified custom data type you previously configured. + +A [custom data type](https://docs.codat.io/using-the-api/custom-data) is an additional data type you can create that is not included in Codat's standardized data model.s endpoint returns a paginated list of records whose schema is defined [Configure custom data type](https://docs.codat.io/platform-api#/operations/configure-custom-data-type) + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.custom_data_type.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "custom_data_identifier": "DynamicsPurchaseOrders", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `request` | [operations.ListCustomDataTypeRecordsRequest](../../models/operations/listcustomdatatyperecordsrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.CustomDataTypeRecords](../../models/shared/customdatatyperecords.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------------------------- | --------------------------------- | --------------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429, 451 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## refresh + +The *Refresh custom data type* endpoint refreshes the specified custom data type for a given company. This is an asynchronous operation that will sync updated data from the linked integration into Codat for you to view. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.custom_data_type.refresh(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "custom_data_identifier": "DynamicsPurchaseOrders", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `request` | [operations.RefreshCustomDataTypeRequest](../../models/operations/refreshcustomdatatyperequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.PullOperation](../../models/shared/pulloperation.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429, 451 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/platform/docs/sdks/integrations/README.md b/platform/docs/sdks/integrations/README.md index c8f11860a..c55d1fe2a 100644 --- a/platform/docs/sdks/integrations/README.md +++ b/platform/docs/sdks/integrations/README.md @@ -1,150 +1,150 @@ -# Integrations - -## Overview - -Get a list of integrations supported by Codat and their logos. - -### Available Operations - -* [get](#get) - Get integration -* [get_branding](#get_branding) - Get branding -* [list](#list) - List integrations - -## get - -Get single integration, by platformKey - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.integrations.get(request={ - "platform_key": "gbol", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `request` | [operations.GetIntegrationRequest](../../models/operations/getintegrationrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Integration](../../models/shared/integration.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get_branding - -Get branding for platform. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.integrations.get_branding(request={ - "platform_key": "gbol", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | -| `request` | [operations.GetIntegrationsBrandingRequest](../../models/operations/getintegrationsbrandingrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Branding](../../models/shared/branding.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## list - -List your available integrations - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.integrations.list(request={ - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `request` | [operations.ListIntegrationsRequest](../../models/operations/listintegrationsrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Integrations](../../models/shared/integrations.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Integrations + +## Overview + +Get a list of integrations supported by Codat and their logos. + +### Available Operations + +* [get](#get) - Get integration +* [get_branding](#get_branding) - Get branding +* [list](#list) - List integrations + +## get + +Get single integration, by platformKey + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.integrations.get(request={ + "platform_key": "gbol", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `request` | [operations.GetIntegrationRequest](../../models/operations/getintegrationrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Integration](../../models/shared/integration.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get_branding + +Get branding for platform. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.integrations.get_branding(request={ + "platform_key": "gbol", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `request` | [operations.GetIntegrationsBrandingRequest](../../models/operations/getintegrationsbrandingrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Branding](../../models/shared/branding.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## list + +List your available integrations + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.integrations.list(request={ + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `request` | [operations.ListIntegrationsRequest](../../models/operations/listintegrationsrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Integrations](../../models/shared/integrations.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/platform/docs/sdks/pushdata/README.md b/platform/docs/sdks/pushdata/README.md index 9a19cedcd..c081a2aa1 100644 --- a/platform/docs/sdks/pushdata/README.md +++ b/platform/docs/sdks/pushdata/README.md @@ -1,162 +1,161 @@ -# PushData - -## Overview - -Initiate and monitor Create, Update, and Delete operations. - -### Available Operations - -* [get_model_options](#get_model_options) - Get push options -* [get_operation](#get_operation) - Get push operation -* [list_operations](#list_operations) - List push operations - -## get_model_options - -This is the generic documentation for creation and updating of data. See the equivalent endpoint for a given data type for more specific information. - -Before pushing data into accounting software, it is often necessary to collect some details from the user as to how they would like the data to be inserted. This includes names and amounts on transactional entities, but also factors such as categorisation of entities, which is often handled differently between different accounting software. A good example of this is specifying where on the balance sheet/profit and loss reports the user would like a newly-created nominal account to appear. - -Codat tries not to limit users to pushing to a very limited number of standard categories, so we have implemented "options" endpoints, which allow us to expose to our clients the fields which are required to be pushed for a specific linked company, and the options which may be selected for each field. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.push_data.get_model_options(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "data_type": shared.SchemaDataType.INVOICES, - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | -| `request` | [operations.GetCreateUpdateModelOptionsByDataTypeRequest](../../models/operations/getcreateupdatemodeloptionsbydatatyperequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.PushOption](../../models/shared/pushoption.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get_operation - -The **Get push operation** endpoint returns a specific [push operation](/using-the-api/push) identified by the `pushOperationKey` that was performed on the company. - -Write operations are actions that send requests to Codat, enabling the creation, updating, deletion of records, or uploading attachments in the connected accounting software. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.push_data.get_operation(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "push_operation_key": "660e8684-c0fb-4468-9e2a-b2e3b115d747", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `request` | [operations.GetPushOperationRequest](../../models/operations/getpushoperationrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.PushOperation](../../models/shared/pushoperation.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## list_operations - -The **List push operations** endpoint returns a list of [push operations](/using-the-api/push) performed on the company. - -Write operations are actions that send requests to Codat, enabling the creation, updating, deletion of records, or uploading attachments in the connected accounting software. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.push_data.list_operations(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `request` | [operations.GetCompanyPushHistoryRequest](../../models/operations/getcompanypushhistoryrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.PushOperations](../../models/shared/pushoperations.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# PushData + +## Overview + +Initiate and monitor Create, Update, and Delete operations. + +### Available Operations + +* [get_model_options](#get_model_options) - Get push options +* [get_operation](#get_operation) - Get push operation +* [list_operations](#list_operations) - List push operations + +## get_model_options + +This is the generic documentation for creation and updating of data. See the equivalent endpoint for a given data type for more specific information. + +Before pushing data into accounting software, it is often necessary to collect some details from the user as to how they would like the data to be inserted. This includes names and amounts on transactional entities, but also factors such as categorisation of entities, which is often handled differently between different accounting software. A good example of this is specifying where on the balance sheet/profit and loss reports the user would like a newly-created nominal account to appear. + +Codat tries not to limit users to pushing to a very limited number of standard categories, so we have implemented "options" endpoints, which allow us to expose to our clients the fields which are required to be pushed for a specific linked company, and the options which may be selected for each field. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.push_data.get_model_options(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "data_type": shared.SchemaDataType.INVOICES, + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | +| `request` | [operations.GetCreateUpdateModelOptionsByDataTypeRequest](../../models/operations/getcreateupdatemodeloptionsbydatatyperequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.PushOption](../../models/shared/pushoption.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get_operation + +The **Get push operation** endpoint returns a specific [push operation](/using-the-api/push) identified by the `pushOperationKey` that was performed on the company. + +Write operations are actions that send requests to Codat, enabling the creation, updating, deletion of records, or uploading attachments in the connected accounting software. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.push_data.get_operation(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `request` | [operations.GetPushOperationRequest](../../models/operations/getpushoperationrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.PushOperation](../../models/shared/pushoperation.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## list_operations + +The **List push operations** endpoint returns a list of [push operations](/using-the-api/push) performed on the company. + +Write operations are actions that send requests to Codat, enabling the creation, updating, deletion of records, or uploading attachments in the connected accounting software. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.push_data.list_operations(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `request` | [operations.GetCompanyPushHistoryRequest](../../models/operations/getcompanypushhistoryrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.PushOperations](../../models/shared/pushoperations.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/platform/docs/sdks/readdata/README.md b/platform/docs/sdks/readdata/README.md index 98d149100..1a9b0175c 100644 --- a/platform/docs/sdks/readdata/README.md +++ b/platform/docs/sdks/readdata/README.md @@ -1,61 +1,60 @@ -# ReadData - -## Overview - -View validation outcomes for completed read data operations. - -### Available Operations - -* [get_validation_results](#get_validation_results) - Get validation results - -## get_validation_results - -Use the **Get validation results** endpoint to review warnings and errors encountered during the data type validation phase. - -The validation result [schema](https://docs.codat.io/platform-api#/schemas/ValidationResult) contains two message arrays: - -- **`warnings`** array lists potential issues with the data type that may require attention but don't block usage. -- **`errors`** array contains critical issues that must be resolved before the data type can be used. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.read_data.get_validation_results(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "dataset_id": "0812af6e-436a-491f-9056-db91cb961ad3", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -| `request` | [operations.GetReadValidationResultsRequest](../../models/operations/getreadvalidationresultsrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.ValidationResult](../../models/shared/validationresult.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# ReadData + +## Overview + +View validation outcomes for completed read data operations. + +### Available Operations + +* [get_validation_results](#get_validation_results) - Get validation results + +## get_validation_results + +Use the **Get validation results** endpoint to review warnings and errors encountered during the data type validation phase. + +The validation result [schema](https://docs.codat.io/platform-api#/schemas/ValidationResult) contains two message arrays: + +- **`warnings`** array lists potential issues with the data type that may require attention but don't block usage. +- **`errors`** array contains critical issues that must be resolved before the data type can be used. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.read_data.get_validation_results(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| `request` | [operations.GetReadValidationResultsRequest](../../models/operations/getreadvalidationresultsrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.ValidationResult](../../models/shared/validationresult.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/platform/docs/sdks/refreshdata/README.md b/platform/docs/sdks/refreshdata/README.md index 5c334e763..ce06da958 100644 --- a/platform/docs/sdks/refreshdata/README.md +++ b/platform/docs/sdks/refreshdata/README.md @@ -1,248 +1,247 @@ -# RefreshData - -## Overview - -Initiate data refreshes, view pull status and history. - -### Available Operations - -* [all](#all) - Refresh all data -* [by_data_type](#by_data_type) - Refresh data type -* [get](#get) - Get data status -* [get_pull_operation](#get_pull_operation) - Get pull operation -* [list_pull_operations](#list_pull_operations) - List pull operations - -## all - -Refreshes all data types with `fetch on first link` set to `true` for a given company. - -This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. - -[Read more](https://docs.codat.io/core-concepts/data-type-settings) about data type settings and `fetch on first link`. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.refresh_data.all(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Use the SDK ... - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -| `request` | [operations.RefreshCompanyDataRequest](../../models/operations/refreshcompanydatarequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## by_data_type - -Refreshes a given data type for a given company. - -This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.refresh_data.by_data_type(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "data_type": shared.SchemaDataType.INVOICES, - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -| `request` | [operations.RefreshDataTypeRequest](../../models/operations/refreshdatatyperequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.PullOperation](../../models/shared/pulloperation.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get - -Get the state of each data type for a company - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.refresh_data.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | -| `request` | [operations.GetCompanyDataStatusRequest](../../models/operations/getcompanydatastatusrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.DataStatuses](../../models/shared/datastatuses.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get_pull_operation - -Retrieve information about a single dataset or pull operation. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.refresh_data.get_pull_operation(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "dataset_id": "fa5f3e86-bd80-49b8-853c-5fbba4b201f5", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `request` | [operations.GetPullOperationRequest](../../models/operations/getpulloperationrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.PullOperation](../../models/shared/pulloperation.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## list_pull_operations - -Gets the pull operation history (datasets) for a given company. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.refresh_data.list_pull_operations(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -| `request` | [operations.ListPullOperationsRequest](../../models/operations/listpulloperationsrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.PullOperations](../../models/shared/pulloperations.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# RefreshData + +## Overview + +Initiate data refreshes, view pull status and history. + +### Available Operations + +* [all](#all) - Refresh all data +* [by_data_type](#by_data_type) - Refresh data type +* [get](#get) - Get data status +* [get_pull_operation](#get_pull_operation) - Get pull operation +* [list_pull_operations](#list_pull_operations) - List pull operations + +## all + +Refreshes all data types with `fetch on first link` set to `true` for a given company. + +This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. + +[Read more](https://docs.codat.io/core-concepts/data-type-settings) about data type settings and `fetch on first link`. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.refresh_data.all(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| `request` | [operations.RefreshCompanyDataRequest](../../models/operations/refreshcompanydatarequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## by_data_type + +Refreshes a given data type for a given company. + +This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.refresh_data.by_data_type(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "data_type": shared.SchemaDataType.INVOICES, + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `request` | [operations.RefreshDataTypeRequest](../../models/operations/refreshdatatyperequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.PullOperation](../../models/shared/pulloperation.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get + +Get the state of each data type for a company + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.refresh_data.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `request` | [operations.GetCompanyDataStatusRequest](../../models/operations/getcompanydatastatusrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.DataStatuses](../../models/shared/datastatuses.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get_pull_operation + +Retrieve information about a single dataset or pull operation. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.refresh_data.get_pull_operation(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `request` | [operations.GetPullOperationRequest](../../models/operations/getpulloperationrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.PullOperation](../../models/shared/pulloperation.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## list_pull_operations + +Gets the pull operation history (datasets) for a given company. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.refresh_data.list_pull_operations(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| `request` | [operations.ListPullOperationsRequest](../../models/operations/listpulloperationsrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.PullOperations](../../models/shared/pulloperations.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/platform/docs/sdks/settings/README.md b/platform/docs/sdks/settings/README.md index 3ec91cf4a..0bc4ac429 100644 --- a/platform/docs/sdks/settings/README.md +++ b/platform/docs/sdks/settings/README.md @@ -1,553 +1,539 @@ -# Settings - -## Overview - -Manage company profile configuration, sync settings, and API keys. - -### Available Operations - -* [create_api_key](#create_api_key) - Create API key -* [delete_api_key](#delete_api_key) - Delete API key -* [get](#get) - Get CORS settings -* [get_profile](#get_profile) - Get profile -* [get_sync_settings](#get_sync_settings) - Get sync settings -* [list_api_keys](#list_api_keys) - List API keys -* [set](#set) - Set CORS settings -* [update_profile](#update_profile) - Update profile -* [update_sync_settings](#update_sync_settings) - Update all sync settings - -## create_api_key - -Use the *Create API keys* endpoint to generate a new API key for your client. - -[API keys](https://docs.codat.io/platform-api#/schemas/apiKeys) are tokens used to control access to the API. Include this token in the `Authorization` header parameter when making API calls, following the word "Basic" and a space with your API key. - -You can [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat and managing API keys via the Portal UI or API. - -### Tips and pitfalls - -* Your first API key is created for you. Access this key via [Codat's Portal](https://app.codat.io/developers/api-keys). -* If you require multiple API keys, perform multiple calls to the *Create API keys* endpoint. -* The number of API keys is limited to 10. If you have reached the maximum amount of keys, use the *Delete API key* endpoint to delete an unused key first. - -### Example Usage: API key details - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.settings.create_api_key(request={ - "name": "azure-invoice-finance-processor", - }) - - # Handle response - print(res) - -``` -### Example Usage: API key details with name - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.settings.create_api_key(request={ - "name": "azure-invoice-finance-processor", - }) - - # Handle response - print(res) - -``` -### Example Usage: Create API key with name - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.settings.create_api_key(request={ - "name": "azure-invoice-finance-processor", - }) - - # Handle response - print(res) - -``` -### Example Usage: Max length for name reached - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.settings.create_api_key(request={ - "name": "azure-invoice-finance-processor", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | -| `request` | [shared.CreateAPIKey](../../models/shared/createapikey.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.APIKeyDetails](../../models/shared/apikeydetails.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 409, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## delete_api_key - -Use the *Delete API keys* endpoint to delete an existing API key, providing its valid `id` as a parameter. Note that this operation is not reversible. - -[API keys](https://docs.codat.io/platform-api#/schemas/apiKeys) are tokens used to control access to the API. Include this token in the `Authorization` header parameter when making API calls, following the word "Basic" and a space with your API key. - -You can [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat and managing API keys via the Portal UI or API. - -### Tips and pitfalls - -* It is possible to delete the last remaining API key. If this happens, a new key can be created via the [API key management page](https://app.codat.io/developers/api-keys) of the Portal. -* It is possible to delete the API key used to authenticate the *Delete API key* request. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.settings.delete_api_key(request={ - "api_key_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -| `request` | [operations.DeleteAPIKeyRequest](../../models/operations/deleteapikeyrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.ErrorMessage](../../models/shared/errormessage.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get - -The *Get CORS settings* endpoint returns the allowed origins (i.e. your domains) you want to allow cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)) with Codat. - -Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.settings.get() - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.ConnectionManagementAllowedOrigins](../../models/shared/connectionmanagementallowedorigins.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get_profile - -Fetch your Codat profile. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.settings.get_profile() - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Profile](../../models/shared/profile.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ------------------- | ------------------- | ------------------- | -| errors.ErrorMessage | 401, 402, 403, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get_sync_settings - -Retrieve the [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings) for your client. This includes how often data types should be queued to be updated, and how much history should be fetched. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.settings.get_sync_settings() - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.SyncSettings](../../models/shared/syncsettings.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ------------------- | ------------------- | ------------------- | -| errors.ErrorMessage | 401, 402, 403, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## list_api_keys - -Use the *List API keys* endpoint to return a list of all API keys that currently exist for your client. This includes keys created via the Portal UI or the *Create API keys* endpoint. - -[API keys](https://docs.codat.io/platform-api#/schemas/apiKeys) are tokens used to control access to the API. Include this token in the `Authorization` header parameter when making API calls, following the word "Basic" and a space with your API key. - -You can [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat and managing API keys via the Portal UI or API. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.settings.list_api_keys() - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.APIKeys](../../models/shared/apikeys.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ------------------- | ------------------- | ------------------- | -| errors.ErrorMessage | 401, 402, 403, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## set - -The *Set CORS settings* endpoint allows you to register allowed origins (i.e. your domains) for use in cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)). - -Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. - -### Example Usage: Allowed origins - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.settings.set(request={ - "allowed_origins": [ - "https://www.bank-of-dave.com", - ], - }) - - # Handle response - print(res) - -``` -### Example Usage: Unauthorized - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.settings.set(request={ - "allowed_origins": [ - "https://www.bank-of-dave.com", - ], - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | -| `request` | [shared.ConnectionManagementAllowedOrigins](../../models/shared/connectionmanagementallowedorigins.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.ConnectionManagementAllowedOrigins](../../models/shared/connectionmanagementallowedorigins.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## update_profile - -Update your Codat profile - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.settings.update_profile(request={ - "confirm_company_name": True, - "icon_url": "https://client-images.codat.io/icon/042399f5-d104-4f38-9ce8-cac3524f4e88_3f5623af-d992-4c22-bc08-e58c520a8526.ico", - "logo_url": "https://client-images.codat.io/logo/042399f5-d104-4f38-9ce8-cac3524f4e88_5806cb1f-7342-4c0e-a0a8-99bfbc47b0ff.png", - "name": "Bob's Burgers", - "redirect_url": "https://bobs-burgers.{countrySuffix}/{companyId}", - "white_list_urls": [ - "https://bobs-burgers.com", - "https://bobs-burgers.co.uk", - ], - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | -| `request` | [shared.Profile](../../models/shared/profile.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Profile](../../models/shared/profile.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ------------------- | ------------------- | ------------------- | -| errors.ErrorMessage | 401, 402, 403, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## update_sync_settings - -Update sync settings for all data types. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.settings.update_sync_settings(request={ - "client_id": "9807ce3e-cfa5-4370-b4f2-09c282b1598b", - "settings": [ - { - "data_type": shared.DataType.INVOICES, - "fetch_on_first_link": True, - "is_locked": True, - "months_to_sync": 24, - "sync_from_utc": "2020-01-01T12:00:00.000Z", - "sync_from_window": 24, - "sync_order": 0, - "sync_schedule": 24, - }, - ], - }) - - # Use the SDK ... - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | -| `request` | [operations.UpdateProfileSyncSettingsRequestBody](../../models/operations/updateprofilesyncsettingsrequestbody.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Errors - -| Error Type | Status Code | Content Type | -| ------------------- | ------------------- | ------------------- | -| errors.ErrorMessage | 401, 402, 403, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Settings + +## Overview + +Manage company profile configuration, sync settings, and API keys. + +### Available Operations + +* [create_api_key](#create_api_key) - Create API key +* [delete_api_key](#delete_api_key) - Delete API key +* [get](#get) - Get CORS settings +* [get_profile](#get_profile) - Get profile +* [get_sync_settings](#get_sync_settings) - Get sync settings +* [list_api_keys](#list_api_keys) - List API keys +* [set](#set) - Set CORS settings +* [update_profile](#update_profile) - Update profile +* [update_sync_settings](#update_sync_settings) - Update all sync settings + +## create_api_key + +Use the *Create API keys* endpoint to generate a new API key for your client. + +[API keys](https://docs.codat.io/platform-api#/schemas/apiKeys) are tokens used to control access to the API. Include this token in the `Authorization` header parameter when making API calls, following the word "Basic" and a space with your API key. + +You can [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat and managing API keys via the Portal UI or API. + +### Tips and pitfalls + +* Your first API key is created for you. Access this key via [Codat's Portal](https://app.codat.io/developers/api-keys). +* If you require multiple API keys, perform multiple calls to the *Create API keys* endpoint. +* The number of API keys is limited to 10. If you have reached the maximum amount of keys, use the *Delete API key* endpoint to delete an unused key first. + +### Example Usage: API key details + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.settings.create_api_key(request={ + "name": "azure-invoice-finance-processor", + }) + + # Handle response + print(res) + +``` +### Example Usage: API key details with name + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.settings.create_api_key(request={ + "name": "azure-invoice-finance-processor", + }) + + # Handle response + print(res) + +``` +### Example Usage: Create API key with name + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.settings.create_api_key(request={ + "name": "azure-invoice-finance-processor", + }) + + # Handle response + print(res) + +``` +### Example Usage: Max length for name reached + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.settings.create_api_key(request={ + "name": "azure-invoice-finance-processor", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `request` | [shared.CreateAPIKey](../../models/shared/createapikey.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.APIKeyDetails](../../models/shared/apikeydetails.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 409, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## delete_api_key + +Use the *Delete API keys* endpoint to delete an existing API key, providing its valid `id` as a parameter. Note that this operation is not reversible. + +[API keys](https://docs.codat.io/platform-api#/schemas/apiKeys) are tokens used to control access to the API. Include this token in the `Authorization` header parameter when making API calls, following the word "Basic" and a space with your API key. + +You can [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat and managing API keys via the Portal UI or API. + +### Tips and pitfalls + +* It is possible to delete the last remaining API key. If this happens, a new key can be created via the [API key management page](https://app.codat.io/developers/api-keys) of the Portal. +* It is possible to delete the API key used to authenticate the *Delete API key* request. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.settings.delete_api_key(request={ + "api_key_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `request` | [operations.DeleteAPIKeyRequest](../../models/operations/deleteapikeyrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.ErrorMessage](../../models/shared/errormessage.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get + +The *Get CORS settings* endpoint returns the allowed origins (i.e. your domains) you want to allow cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)) with Codat. + +Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.settings.get() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.ConnectionManagementAllowedOrigins](../../models/shared/connectionmanagementallowedorigins.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get_profile + +Fetch your Codat profile. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.settings.get_profile() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Profile](../../models/shared/profile.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ------------------- | ------------------- | ------------------- | +| errors.ErrorMessage | 401, 402, 403, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get_sync_settings + +Retrieve the [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings) for your client. This includes how often data types should be queued to be updated, and how much history should be fetched. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.settings.get_sync_settings() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.SyncSettings](../../models/shared/syncsettings.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ------------------- | ------------------- | ------------------- | +| errors.ErrorMessage | 401, 402, 403, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## list_api_keys + +Use the *List API keys* endpoint to return a list of all API keys that currently exist for your client. This includes keys created via the Portal UI or the *Create API keys* endpoint. + +[API keys](https://docs.codat.io/platform-api#/schemas/apiKeys) are tokens used to control access to the API. Include this token in the `Authorization` header parameter when making API calls, following the word "Basic" and a space with your API key. + +You can [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat and managing API keys via the Portal UI or API. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.settings.list_api_keys() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.APIKeys](../../models/shared/apikeys.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ------------------- | ------------------- | ------------------- | +| errors.ErrorMessage | 401, 402, 403, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## set + +The *Set CORS settings* endpoint allows you to register allowed origins (i.e. your domains) for use in cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)). + +Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. + +### Example Usage: Allowed origins + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.settings.set(request={ + "allowed_origins": [ + "https://www.bank-of-dave.com", + ], + }) + + # Handle response + print(res) + +``` +### Example Usage: Unauthorized + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.settings.set(request={ + "allowed_origins": [ + "https://www.bank-of-dave.com", + ], + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `request` | [shared.ConnectionManagementAllowedOrigins](../../models/shared/connectionmanagementallowedorigins.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.ConnectionManagementAllowedOrigins](../../models/shared/connectionmanagementallowedorigins.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## update_profile + +Update your Codat profile + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.settings.update_profile(request={ + "confirm_company_name": True, + "icon_url": "https://client-images.codat.io/icon/042399f5-d104-4f38-9ce8-cac3524f4e88_3f5623af-d992-4c22-bc08-e58c520a8526.ico", + "logo_url": "https://client-images.codat.io/logo/042399f5-d104-4f38-9ce8-cac3524f4e88_5806cb1f-7342-4c0e-a0a8-99bfbc47b0ff.png", + "name": "Bob's Burgers", + "redirect_url": "https://bobs-burgers.{countrySuffix}/{companyId}", + "white_list_urls": [ + "https://bobs-burgers.com", + "https://bobs-burgers.co.uk", + ], + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `request` | [shared.Profile](../../models/shared/profile.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Profile](../../models/shared/profile.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ------------------- | ------------------- | ------------------- | +| errors.ErrorMessage | 401, 402, 403, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## update_sync_settings + +Update sync settings for all data types. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.settings.update_sync_settings(request={}) + + # Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | +| `request` | [operations.UpdateProfileSyncSettingsRequestBody](../../models/operations/updateprofilesyncsettingsrequestbody.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Errors + +| Error Type | Status Code | Content Type | +| ------------------- | ------------------- | ------------------- | +| errors.ErrorMessage | 401, 402, 403, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/platform/docs/sdks/supplementaldata/README.md b/platform/docs/sdks/supplementaldata/README.md index b855ae4f2..12c10dcb8 100644 --- a/platform/docs/sdks/supplementaldata/README.md +++ b/platform/docs/sdks/supplementaldata/README.md @@ -1,280 +1,268 @@ -# SupplementalData - -## Overview - -Configure and pull additional data you can include in Codat's standard data types. - -### Available Operations - -* [configure](#configure) - Configure -* [get_configuration](#get_configuration) - Get configuration - -## configure - -The *Configure* endpoint allows you to maintain or change configuration required to return supplemental data for each integration and data type combination. - -[Supplemental data](https://docs.codat.io/using-the-api/supplemental-data/overview) is additional data you can include in Codat's standard data types. - -**Integration-specific behavior** -See the *examples* for integration-specific frequently requested properties. - -### Example Usage: QBO - Customers - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import operations, shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.supplemental_data.configure(request={ - "supplemental_data_configuration": {}, - "data_type": operations.DataType.INVOICES, - "platform_key": "gbol", - }) - - # Use the SDK ... - -``` -### Example Usage: QBO - Invoices - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import operations, shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.supplemental_data.configure(request={ - "supplemental_data_configuration": {}, - "data_type": operations.DataType.INVOICES, - "platform_key": "gbol", - }) - - # Use the SDK ... - -``` -### Example Usage: Unauthorized - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import operations, shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.supplemental_data.configure(request={ - "supplemental_data_configuration": { - "supplemental_data_config": { - "orders-supplemental-data": { - "data_source": "/orders", - "pull_data": { - "orderNumber": "order_num", - }, - "push_data": { - "orderNumber": "order_num", - }, - }, - }, - }, - "data_type": operations.DataType.INVOICES, - "platform_key": "gbol", - }) - - # Use the SDK ... - -``` -### Example Usage: Xero - Accounts - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import operations, shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.supplemental_data.configure(request={ - "supplemental_data_configuration": {}, - "data_type": operations.DataType.INVOICES, - "platform_key": "gbol", - }) - - # Use the SDK ... - -``` -### Example Usage: Xero - Contacts - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import operations, shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.supplemental_data.configure(request={ - "supplemental_data_configuration": {}, - "data_type": operations.DataType.INVOICES, - "platform_key": "gbol", - }) - - # Use the SDK ... - -``` -### Example Usage: Xero - Invoices - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import operations, shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.supplemental_data.configure(request={ - "supplemental_data_configuration": {}, - "data_type": operations.DataType.INVOICES, - "platform_key": "gbol", - }) - - # Use the SDK ... - -``` -### Example Usage: Xero - Items - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import operations, shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.supplemental_data.configure(request={ - "supplemental_data_configuration": {}, - "data_type": operations.DataType.INVOICES, - "platform_key": "gbol", - }) - - # Use the SDK ... - -``` -### Example Usage: Xero - Tax rates - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import operations, shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.supplemental_data.configure(request={ - "supplemental_data_configuration": {}, - "data_type": operations.DataType.INVOICES, - "platform_key": "gbol", - }) - - # Use the SDK ... - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `request` | [operations.ConfigureSupplementalDataRequest](../../models/operations/configuresupplementaldatarequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get_configuration - -The *Get configuration* endpoint returns supplemental data configuration previously created for each integration and data type combination. - -[Supplemental data](https://docs.codat.io/using-the-api/supplemental-data/overview) is additional data you can include in Codat's standard data types. - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import operations, shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.supplemental_data.get_configuration(request={ - "data_type": operations.PathParamDataType.INVOICES, - "platform_key": "gbol", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | -| `request` | [operations.GetSupplementalDataConfigurationRequest](../../models/operations/getsupplementaldataconfigurationrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.SupplementalDataConfiguration](../../models/shared/supplementaldataconfiguration.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# SupplementalData + +## Overview + +Configure and pull additional data you can include in Codat's standard data types. + +### Available Operations + +* [configure](#configure) - Configure +* [get_configuration](#get_configuration) - Get configuration + +## configure + +The *Configure* endpoint allows you to maintain or change configuration required to return supplemental data for each integration and data type combination. + +[Supplemental data](https://docs.codat.io/using-the-api/supplemental-data/overview) is additional data you can include in Codat's standard data types. + +**Integration-specific behavior** +See the *examples* for integration-specific frequently requested properties. + +### Example Usage: QBO - Customers + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.supplemental_data.configure(request={ + "supplemental_data_configuration": {}, + "data_type": "invoices", + "platform_key": "gbol", + }) + + # Use the SDK ... + +``` +### Example Usage: QBO - Invoices + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.supplemental_data.configure(request={ + "supplemental_data_configuration": {}, + "data_type": "invoices", + "platform_key": "gbol", + }) + + # Use the SDK ... + +``` +### Example Usage: Unauthorized + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.supplemental_data.configure(request={ + "supplemental_data_configuration": {}, + "data_type": "invoices", + "platform_key": "gbol", + }) + + # Use the SDK ... + +``` +### Example Usage: Xero - Accounts + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.supplemental_data.configure(request={ + "supplemental_data_configuration": {}, + "data_type": "invoices", + "platform_key": "gbol", + }) + + # Use the SDK ... + +``` +### Example Usage: Xero - Contacts + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.supplemental_data.configure(request={ + "supplemental_data_configuration": {}, + "data_type": "invoices", + "platform_key": "gbol", + }) + + # Use the SDK ... + +``` +### Example Usage: Xero - Invoices + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.supplemental_data.configure(request={ + "supplemental_data_configuration": {}, + "data_type": "invoices", + "platform_key": "gbol", + }) + + # Use the SDK ... + +``` +### Example Usage: Xero - Items + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.supplemental_data.configure(request={ + "supplemental_data_configuration": {}, + "data_type": "invoices", + "platform_key": "gbol", + }) + + # Use the SDK ... + +``` +### Example Usage: Xero - Tax rates + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.supplemental_data.configure(request={ + "supplemental_data_configuration": {}, + "data_type": "invoices", + "platform_key": "gbol", + }) + + # Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `request` | [operations.ConfigureSupplementalDataRequest](../../models/operations/configuresupplementaldatarequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get_configuration + +The *Get configuration* endpoint returns supplemental data configuration previously created for each integration and data type combination. + +[Supplemental data](https://docs.codat.io/using-the-api/supplemental-data/overview) is additional data you can include in Codat's standard data types. + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.supplemental_data.get_configuration(request={ + "data_type": "invoices", + "platform_key": "gbol", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | +| `request` | [operations.GetSupplementalDataConfigurationRequest](../../models/operations/getsupplementaldataconfigurationrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.SupplementalDataConfiguration](../../models/shared/supplementaldataconfiguration.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/platform/docs/sdks/webhooks/README.md b/platform/docs/sdks/webhooks/README.md index 3871cef24..3220b1d87 100644 --- a/platform/docs/sdks/webhooks/README.md +++ b/platform/docs/sdks/webhooks/README.md @@ -1,180 +1,232 @@ -# Webhooks - -## Overview - -Create and manage webhooks that listen to Codat's events. - -### Available Operations - -* [create_consumer](#create_consumer) - Create webhook consumer -* [delete_consumer](#delete_consumer) - Delete webhook consumer -* [list_consumers](#list_consumers) - List webhook consumers - -## create_consumer - -Use the *Create webhook consumer* endpoint to create a new webhook consumer that will listen to messages we send you. - -[Webhook consumer](https://docs.codat.io/platform-api#/schemas/WebhookConsumer) is an HTTP endpoint that you configure to subscribe to specific events. See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). - -### Tips and traps -- The number of webhook consumers you can create is limited to 50. If you have reached the maximum number of consumers, use the [*Delete webhook consumer*](https://docs.codat.io/platform-api#/operations/delete-webhook-consumer) endpoint to delete an unused consumer first. - -### Example Usage: Subscribe consumer to one or more event types - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.webhooks.create_consumer(request={ - "event_types": [ - "DataSyncCompleted", - "Dataset data changed", - ], - "url": "https://example.com/webhoook-consumer", - }) - - # Handle response - print(res) - -``` -### Example Usage: Subscribe consumer with disabled endpoint - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.webhooks.create_consumer(request={ - "disabled": True, - "event_types": [ - "DataSyncCompleted", - ], - "url": "https://example.com/webhoook-consumer", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `request` | [shared.WebhookConsumerPrototype](../../models/shared/webhookconsumerprototype.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.WebhookConsumer](../../models/shared/webhookconsumer.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## delete_consumer - -Use the *Delete webhook consumer* endpoint to delete an existing webhoook consumer, providing its valid `id` as a parameter. - -[Webhook consumer](https://docs.codat.io/platform-api#/schemas/WebhookConsumer) is an HTTP endpoint that you configure to subscribe to specific events. See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - cp_client.webhooks.delete_consumer(request={ - "webhook_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Use the SDK ... - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `request` | [operations.DeleteWebhookConsumerRequest](../../models/operations/deletewebhookconsumerrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## list_consumers - -Use the *List webhook consumers* endpoint to return a list of all webhook consumers that currently exist for your client. - -[Webhook consumer](https://docs.codat.io/platform-api#/schemas/WebhookConsumer) is an HTTP endpoint that you configure to subscribe to specific events. See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). - -### Example Usage - - -```python -from codat_platform import CodatPlatform -from codat_platform.models import shared - - -with CodatPlatform( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as cp_client: - - res = cp_client.webhooks.list_consumers() - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.WebhookConsumers](../../models/shared/webhookconsumers.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file +# Webhooks + +## Overview + +Create and manage webhooks that listen to Codat's events. + +### Available Operations + +* [create_consumer](#create_consumer) - Create webhook consumer +* [delete_consumer](#delete_consumer) - Delete webhook consumer +* [list_consumers](#list_consumers) - List webhook consumers +* [rotate_zapier_key](#rotate_zapier_key) - Rotate Zapier key + +## create_consumer + +Use the *Create webhook consumer* endpoint to create a new webhook consumer that will listen to messages we send you. + +[Webhook consumer](https://docs.codat.io/platform-api#/schemas/WebhookConsumer) is an HTTP endpoint that you configure to subscribe to specific events. See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). + +### Tips and traps +- The number of webhook consumers you can create is limited to 50. If you have reached the maximum number of consumers, use the [*Delete webhook consumer*](https://docs.codat.io/platform-api#/operations/delete-webhook-consumer) endpoint to delete an unused consumer first. + +### Example Usage: Subscribe consumer to one or more event types + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.webhooks.create_consumer(request={ + "event_types": [ + "DataSyncCompleted", + "Dataset data changed", + ], + "url": "https://example.com/webhoook-consumer", + }) + + # Handle response + print(res) + +``` +### Example Usage: Subscribe consumer with disabled endpoint + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.webhooks.create_consumer(request={ + "disabled": True, + "event_types": [ + "DataSyncCompleted", + ], + "url": "https://example.com/webhoook-consumer", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `request` | [shared.WebhookConsumerPrototype](../../models/shared/webhookconsumerprototype.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.WebhookConsumer](../../models/shared/webhookconsumer.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## delete_consumer + +Use the *Delete webhook consumer* endpoint to delete an existing webhoook consumer, providing its valid `id` as a parameter. + +[Webhook consumer](https://docs.codat.io/platform-api#/schemas/WebhookConsumer) is an HTTP endpoint that you configure to subscribe to specific events. See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + cp_client.webhooks.delete_consumer(request={ + "webhook_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `request` | [operations.DeleteWebhookConsumerRequest](../../models/operations/deletewebhookconsumerrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## list_consumers + +Use the *List webhook consumers* endpoint to return a list of all webhook consumers that currently exist for your client. + +[Webhook consumer](https://docs.codat.io/platform-api#/schemas/WebhookConsumer) is an HTTP endpoint that you configure to subscribe to specific events. See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.webhooks.list_consumers() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.WebhookConsumers](../../models/shared/webhookconsumers.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## rotate_zapier_key + +The *Rotate Zapier key* endpoint returns the Zapier integration key needed to configure Zaps triggered by Codat's webhooks. + +If a key has already been created, calling this will revoke that existing key. + +The key changes each time this endpoint is called. If you are already using our Zapier integration and called this endpoint again, you need to reauthenticate using the latest integration key returned in the response. + +Our Zapier integration makes it simple for you to set up and receive user notifications in your preferred ways, such as via email or Slack. See our [Zapier documentation](https://docs.codat.io/using-the-api/webhooks/zapier-integration) for detailed instructions on setting up this integration. + + + +### Example Usage + + +```python +from codat_platform import CodatPlatform +from codat_platform.models import shared + + +with CodatPlatform( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as cp_client: + + res = cp_client.webhooks.rotate_zapier_key() + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------- | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.WebhookZapierKey](../../models/shared/webhookzapierkey.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ------------------- | ------------------- | ------------------- | +| errors.ErrorMessage | 401, 402, 403, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/platform/pyproject.toml b/platform/pyproject.toml index 871479c4e..40d0e3080 100644 --- a/platform/pyproject.toml +++ b/platform/pyproject.toml @@ -1,58 +1,35 @@ - [project] name = "codat-platform" -version = "5.0.1" +version = "5.0.2" description = "Manage the building blocks of Codat, including companies, connections, and more." -authors = [{ name = "Speakeasy" },] +authors = [{ name = "Codat", email = "support@codat.io" }] readme = "README-PYPI.md" -requires-python = ">=3.10" +requires-python = ">=3.8" dependencies = [ - "httpcore >=1.0.9", - "httpx >=0.28.1", - "pydantic >=2.11.2", + "urllib3 >= 1.25.3, < 3.0.0", + "python-dateutil >= 2.8.2", + "pydantic >= 2", + "typing-extensions >= 4.7.1", + "httpx >= 0.28.1", + "httpcore >= 1.0.9", ] +[project.urls] +Repository = "https://github.com/codatio/client-sdk-python.git" + [tool.poetry] -repository = "https://github.com/codatio/client-sdk-python.git" packages = [ - { include = "codat_platform", from = "src" } + { include = "codat_platform", from = "src" }, ] -include = ["py.typed", "src/codat_platform/py.typed"] - -[tool.setuptools.package-data] -"*" = ["py.typed", "src/codat_platform/py.typed"] - -[virtualenvs] -in-project = true +include = ["src/codat_platform/py.typed"] [tool.poetry.group.dev.dependencies] -mypy = "==1.15.0" -pylint = "==3.2.3" -pyright = "==1.1.398" +pytest = ">=7.2.1" +mypy = ">=1.5" [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" [tool.pytest.ini_options] -asyncio_default_fixture_loop_scope = "function" pythonpath = ["src"] - -[tool.mypy] -disable_error_code = "misc" -explicit_package_bases = true -mypy_path = "src" - -[[tool.mypy.overrides]] -module = "typing_inspect" -ignore_missing_imports = true - -[[tool.mypy.overrides]] -module = "jsonpath" -ignore_missing_imports = true - -[tool.pyright] -venvPath = "." -venv = ".venv" - - diff --git a/platform/src/codat_platform/__init__.py b/platform/src/codat_platform/__init__.py index 833c68cd5..1cd8a0cb6 100644 --- a/platform/src/codat_platform/__init__.py +++ b/platform/src/codat_platform/__init__.py @@ -1,4 +1,145 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +# flake8: noqa + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +__version__ = "1.0.0" + +# import apis into sdk package +from codat_platform.api.companies import Companies +from codat_platform.api.connection_management import ConnectionManagement +from codat_platform.api.connections import Connections +from codat_platform.api.cors import Cors +from codat_platform.api.custom_data_type import CustomDataType +from codat_platform.api.integrations import Integrations +from codat_platform.api.push_data import PushData +from codat_platform.api.read_data import ReadData +from codat_platform.api.refresh_data import RefreshData +from codat_platform.api.settings import Settings +from codat_platform.api.supplemental_data import SupplementalData +from codat_platform.api.webhooks import Webhooks + +# import ApiClient +from codat_platform.api_response import ApiResponse +from codat_platform.api_client import ApiClient +from codat_platform.configuration import Configuration +from codat_platform.exceptions import OpenApiException +from codat_platform.exceptions import ApiTypeError +from codat_platform.exceptions import ApiValueError +from codat_platform.exceptions import ApiKeyError +from codat_platform.exceptions import ApiAttributeError +from codat_platform.exceptions import ApiException + +# import models into sdk package +from codat_platform.models.access_token import AccessToken +from codat_platform.models.shared.apikeydetails import APIKeyDetails +from codat_platform.models.shared.apikeydetails import APIKeyDetails as ApiKeyDetails +from codat_platform.models.shared.apikeys import APIKeys +from codat_platform.models.shared.apikeys import APIKeys as ApiKeys +from codat_platform.models.shared.branding import Branding +from codat_platform.models.shared.brandingbutton import BrandingButton +from codat_platform.models.shared.brandingimage import BrandingImage +from codat_platform.models.shared.brandinglogo import BrandingLogo +from codat_platform.models.shared.clientratelimitwebhook import ClientRateLimitWebhook +from codat_platform.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayload +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.company import Company +from codat_platform.models.shared.companyaccesstoken import CompanyAccessToken +from codat_platform.models.shared.companydetails import CompanyDetails +from codat_platform.models.company_product_webhook import CompanyProductWebhook +from codat_platform.models.company_product_webhook_payload import CompanyProductWebhookPayload +from codat_platform.models.shared.companyreference import CompanyReference +from codat_platform.models.company_reference_links import CompanyReferenceLinks +from codat_platform.models.shared.companyrequestbody import CompanyRequestBody +from codat_platform.models.shared.companysyncsettings import CompanySyncSettings +from codat_platform.models.shared.companyupdaterequest import CompanyUpdateRequest +from codat_platform.models.shared.companywebhook import CompanyWebhook +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connectionmanagementaccesstoken import ConnectionManagementAccessToken +from codat_platform.models.shared.connectionmanagementallowedorigins import ConnectionManagementAllowedOrigins +from codat_platform.models.shared.connectionwebhook import ConnectionWebhook +from codat_platform.models.shared.connectionwebhookpayload import ConnectionWebhookPayload +from codat_platform.models.shared.connections import Connections +from codat_platform.models.shared.createapikey import CreateAPIKey +from codat_platform.models.shared.createapikey import CreateAPIKey as CreateApiKey +from codat_platform.models.create_connection_request import CreateConnectionRequest +from codat_platform.models.shared.customdatatypeconfiguration import CustomDataTypeConfiguration +from codat_platform.models.shared.customdatatyperecord import CustomDataTypeRecord +from codat_platform.models.shared.customdatatyperecords import CustomDataTypeRecords +from codat_platform.models.shared.dataconnectionerror import DataConnectionError +from codat_platform.models.shared.dataconnectionstatus import DataConnectionStatus +from codat_platform.models.shared.datastatus import DataStatus +from codat_platform.models.shared.datastatuses import DataStatuses +from codat_platform.models.shared.datatype import DataType +from codat_platform.models.shared.datatypefeature import DataTypeFeature +from codat_platform.models.shared.datatypereadsummary import DataTypeReadSummary +from codat_platform.models.shared.datatypewritewebhook import DataTypeWriteWebhook +from codat_platform.models.shared.datatypewritewebhookpayload import DataTypeWriteWebhookPayload +from codat_platform.models.shared.datatypewritewebhookrecord import DataTypeWriteWebhookRecord +from codat_platform.models.shared.errormessage import ErrorMessage +from codat_platform.models.shared.errorvalidation import ErrorValidation +from codat_platform.models.shared.errorvalidationitem import ErrorValidationItem +from codat_platform.models.shared.featurestate import FeatureState +from codat_platform.models.shared.featuretype import FeatureType +from codat_platform.models.shared.halref import HalRef +from codat_platform.models.shared.imagereference import ImageReference +from codat_platform.models.shared.integration import Integration +from codat_platform.models.shared.integrations import Integrations +from codat_platform.models.shared.issue import Issue +from codat_platform.models.issue_links import IssueLinks +from codat_platform.models.shared.links import Links +from codat_platform.models.modified_date import ModifiedDate +from codat_platform.models.paging_info import PagingInfo +from codat_platform.models.shared.profile import Profile +from codat_platform.models.shared.pulloperation import PullOperation +from codat_platform.models.shared.pulloperations import PullOperations +from codat_platform.models.shared.pushchangetype import PushChangeType +from codat_platform.models.shared.pushfieldvalidation import PushFieldValidation +from codat_platform.models.shared.pushoperation import PushOperation +from codat_platform.models.shared.pushoperationchange import PushOperationChange +from codat_platform.models.shared.pushoperationref import PushOperationRef +from codat_platform.models.shared.pushoperationstatus import PushOperationStatus +from codat_platform.models.shared.pushoperations import PushOperations +from codat_platform.models.shared.pushoption import PushOption +from codat_platform.models.shared.pushoptionchoice import PushOptionChoice +from codat_platform.models.shared.pushoptionproperty import PushOptionProperty +from codat_platform.models.shared.pushoptiontype import PushOptionType +from codat_platform.models.shared.pushvalidationinfo import PushValidationInfo +from codat_platform.models.shared.readcompletedwebhook import ReadCompletedWebhook +from codat_platform.models.shared.readcompletedwebhookpayload import ReadCompletedWebhookPayload +from codat_platform.models.refresh_product_data_request import RefreshProductDataRequest +from codat_platform.models.set_company_sync_settings_request import SetCompanySyncSettingsRequest +from codat_platform.models.shared.sourcetype import SourceType +from codat_platform.models.shared.status import Status +from codat_platform.models.shared.supplementaldataconfiguration import SupplementalDataConfiguration +from codat_platform.models.supplemental_data_source_configuration import SupplementalDataSourceConfiguration +from codat_platform.models.shared.supportedfeature import SupportedFeature +from codat_platform.models.shared.syncsetting import SyncSetting +from codat_platform.models.shared.syncsettings import SyncSettings +from codat_platform.models.shared.updateconnectionstatus import UpdateConnectionStatus +from codat_platform.models.update_profile_sync_settings_request import UpdateProfileSyncSettingsRequest +from codat_platform.models.shared.validation import Validation +from codat_platform.models.shared.validationitem import ValidationItem +from codat_platform.models.shared.validationresult import ValidationResult +from codat_platform.models.shared.webhookconsumer import WebhookConsumer +from codat_platform.models.shared.webhookconsumerprototype import WebhookConsumerPrototype +from codat_platform.models.shared.webhookconsumers import WebhookConsumers +from codat_platform.models.webhook_zapier_key import WebhookZapierKey +from codat_platform.models.shared.writestatus import WriteStatus +from codat_platform.models.shared.writetype import WriteType +from .sdk import CodatPlatform from ._version import ( __title__, @@ -7,11 +148,12 @@ __gen_version__, __user_agent__, ) -from .sdk import * -from .sdkconfiguration import * - - VERSION: str = __version__ -OPENAPI_DOC_VERSION = __openapi_doc_version__ -SPEAKEASY_GENERATOR_VERSION = __gen_version__ -USER_AGENT = __user_agent__ +OPENAPI_DOC_VERSION: str = __openapi_doc_version__ +USER_AGENT: str = __user_agent__ +SPEAKEASY_GENERATOR_VERSION: str = __gen_version__ + +from .utils.retries import ( + RetryConfig as RetryConfig, +) +SERVERS = ['https://api.codat.io'] diff --git a/platform/src/codat_platform/_hooks/__init__.py b/platform/src/codat_platform/_hooks/__init__.py index 2ee66cdd5..9a9b25d03 100644 --- a/platform/src/codat_platform/_hooks/__init__.py +++ b/platform/src/codat_platform/_hooks/__init__.py @@ -1,5 +1,28 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Hooks public surface.""" -from .sdkhooks import * -from .types import * -from .registration import * +from .sdkhooks import SDKHooks, attach_hooks_to_api_client +from .types import ( + AfterErrorContext, + AfterErrorHook, + AfterSuccessContext, + AfterSuccessHook, + BeforeRequestContext, + BeforeRequestHook, + HookContext, + Hooks, + SDKInitHook, +) + +__all__ = [ + "AfterErrorContext", + "AfterErrorHook", + "AfterSuccessContext", + "AfterSuccessHook", + "BeforeRequestContext", + "BeforeRequestHook", + "HookContext", + "Hooks", + "SDKHooks", + "SDKInitHook", + "attach_hooks_to_api_client", +] diff --git a/platform/src/codat_platform/_hooks/sdkhooks.py b/platform/src/codat_platform/_hooks/sdkhooks.py index 702f12794..d130d2d60 100644 --- a/platform/src/codat_platform/_hooks/sdkhooks.py +++ b/platform/src/codat_platform/_hooks/sdkhooks.py @@ -1,19 +1,22 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""SDKHooks registry — mirrors Speakeasy's _hooks/sdkhooks.py. -import httpx +Generated by pipeline/postprocess_generated.py — do not edit by hand. +""" + +from typing import Any, List, Optional, Tuple + +from .registration import init_hooks from .types import ( - SDKInitHook, - BeforeRequestContext, - BeforeRequestHook, - AfterSuccessContext, - AfterSuccessHook, AfterErrorContext, AfterErrorHook, + AfterSuccessContext, + AfterSuccessHook, + BeforeRequestContext, + BeforeRequestHook, + HookContext, Hooks, + SDKInitHook, ) -from .registration import init_hooks -from typing import List, Optional, Tuple -from codat_platform.httpclient import HttpClient class SDKHooks(Hooks): @@ -36,25 +39,20 @@ def register_after_success_hook(self, hook: AfterSuccessHook) -> None: def register_after_error_hook(self, hook: AfterErrorHook) -> None: self.after_error_hooks.append(hook) - def sdk_init(self, base_url: str, client: HttpClient) -> Tuple[str, HttpClient]: + def sdk_init(self, base_url: str, client: Any) -> Tuple[str, Any]: for hook in self.sdk_init_hooks: base_url, client = hook.sdk_init(base_url, client) return base_url, client - def before_request( - self, hook_ctx: BeforeRequestContext, request: httpx.Request - ) -> httpx.Request: + def before_request(self, hook_ctx: BeforeRequestContext, request: Any) -> Any: for hook in self.before_request_hooks: out = hook.before_request(hook_ctx, request) if isinstance(out, Exception): raise out request = out - return request - def after_success( - self, hook_ctx: AfterSuccessContext, response: httpx.Response - ) -> httpx.Response: + def after_success(self, hook_ctx: AfterSuccessContext, response: Any) -> Any: for hook in self.after_success_hooks: out = hook.after_success(hook_ctx, response) if isinstance(out, Exception): @@ -65,12 +63,85 @@ def after_success( def after_error( self, hook_ctx: AfterErrorContext, - response: Optional[httpx.Response], + response: Optional[Any], error: Optional[Exception], - ) -> Tuple[Optional[httpx.Response], Optional[Exception]]: + ) -> Tuple[Optional[Any], Optional[Exception]]: for hook in self.after_error_hooks: result = hook.after_error(hook_ctx, response, error) if isinstance(result, Exception): raise result response, error = result return response, error + + +def attach_hooks_to_api_client( + api_client: Any, + hooks: SDKHooks, + base_url: str = "", + security_source: Any = None, + auth_headers: Optional[List[Tuple[str, str]]] = None, +) -> None: + """Wrap api_client.call_api so registered hooks fire around each request. + + Notes: + - operation_id is the real spec operation id (e.g. "create-company"), + matching Speakeasy. Each generated method passes it to call_api as the + operation_id keyword; it defaults to "" only if a caller reaches + call_api without going through a generated method. The value comes from + the same source of truth the TypeScript arm uses (the x-codat-operation-id + vendor extension, set in preprocess_oas.py). + - The request and response objects are urllib3-flavoured, not httpx — + consistent with our ApiClient. Hook authors should treat them opaquely. + - security_source is the value passed to the SDK constructor. It may be a + Security model or a zero-argument callable that returns one (Speakeasy's + pattern for rotating credentials). It is resolved on every request so a + rotating credential is picked up each time, and each (field, header) in + auth_headers is set from the resolved value. + """ + original_call_api = api_client.call_api + resolved_auth_headers = auth_headers or [] + + def apply_security(headers): + if security_source is None or not resolved_auth_headers: + return + resolved = security_source() if callable(security_source) else security_source + for field_name, header_name in resolved_auth_headers: + value = getattr(resolved, field_name, None) + if value is not None: + headers[header_name] = value + + def wrapped(method, url, header_params=None, body=None, post_params=None, _request_timeout=None, operation_id=""): + headers = dict(header_params or {}) + apply_security(headers) + hook_ctx = HookContext( + config=None, + base_url=base_url, + operation_id=operation_id, + oauth2_scopes=None, + security_source=security_source, + ) + request = { + "method": method, + "url": url, + "headers": headers, + "body": body, + "post_params": post_params, + } + request = hooks.before_request(BeforeRequestContext(hook_ctx), request) + try: + response = original_call_api( + method=request["method"], + url=request["url"], + header_params=request["headers"], + body=request["body"], + post_params=request.get("post_params"), + _request_timeout=_request_timeout, + ) + except Exception as e: + new_response, new_error = hooks.after_error(AfterErrorContext(hook_ctx), None, e) + if new_error is not None: + raise new_error + return new_response + return hooks.after_success(AfterSuccessContext(hook_ctx), response) + + api_client.call_api = wrapped diff --git a/platform/src/codat_platform/_hooks/types.py b/platform/src/codat_platform/_hooks/types.py index 4be3caf31..5abf97b02 100644 --- a/platform/src/codat_platform/_hooks/types.py +++ b/platform/src/codat_platform/_hooks/types.py @@ -1,14 +1,26 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Hooks abstract surface — mirrors Speakeasy's _hooks/types.py. + +Generated by pipeline/postprocess_generated.py — do not edit by hand. + +Class names and method signatures match Speakeasy bit-for-bit so SDK-author code +that registers hook implementations can be ported unchanged. The two deviations +from the Speakeasy SDK are intentional and documented in FEATURE-AUDIT.md: + + 1. Request/response types are typed as Any here. Speakeasy uses httpx.Request / + httpx.Response. Our OAG pipeline uses urllib3 via ApiClient, so we use Any + to avoid forcing httpx as a transitive dependency. Hook implementations + should treat the request and response parameters as opaque dicts/objects + produced by ApiClient. + 2. HookContext.config is Any. Speakeasy ships an SDKConfiguration class; we + do not. +""" from abc import ABC, abstractmethod -from codat_platform.httpclient import HttpClient -from codat_platform.sdkconfiguration import SDKConfiguration -import httpx from typing import Any, Callable, List, Optional, Tuple, Union class HookContext: - config: SDKConfiguration + config: Any base_url: str operation_id: str oauth2_scopes: Optional[List[str]] = None @@ -16,12 +28,12 @@ class HookContext: def __init__( self, - config: SDKConfiguration, + config: Any, base_url: str, operation_id: str, - oauth2_scopes: Optional[List[str]], - security_source: Optional[Union[Any, Callable[[], Any]]], - ): + oauth2_scopes: Optional[List[str]] = None, + security_source: Optional[Union[Any, Callable[[], Any]]] = None, + ) -> None: self.config = config self.base_url = base_url self.operation_id = operation_id @@ -64,24 +76,20 @@ def __init__(self, hook_ctx: HookContext): class SDKInitHook(ABC): @abstractmethod - def sdk_init(self, base_url: str, client: HttpClient) -> Tuple[str, HttpClient]: - pass + def sdk_init(self, base_url: str, client: Any) -> Tuple[str, Any]: + ... class BeforeRequestHook(ABC): @abstractmethod - def before_request( - self, hook_ctx: BeforeRequestContext, request: httpx.Request - ) -> Union[httpx.Request, Exception]: - pass + def before_request(self, hook_ctx: BeforeRequestContext, request: Any) -> Union[Any, Exception]: + ... class AfterSuccessHook(ABC): @abstractmethod - def after_success( - self, hook_ctx: AfterSuccessContext, response: httpx.Response - ) -> Union[httpx.Response, Exception]: - pass + def after_success(self, hook_ctx: AfterSuccessContext, response: Any) -> Union[Any, Exception]: + ... class AfterErrorHook(ABC): @@ -89,25 +97,25 @@ class AfterErrorHook(ABC): def after_error( self, hook_ctx: AfterErrorContext, - response: Optional[httpx.Response], + response: Optional[Any], error: Optional[Exception], - ) -> Union[Tuple[Optional[httpx.Response], Optional[Exception]], Exception]: - pass + ) -> Union[Tuple[Optional[Any], Optional[Exception]], Exception]: + ... class Hooks(ABC): @abstractmethod - def register_sdk_init_hook(self, hook: SDKInitHook): - pass + def register_sdk_init_hook(self, hook: SDKInitHook) -> None: + ... @abstractmethod - def register_before_request_hook(self, hook: BeforeRequestHook): - pass + def register_before_request_hook(self, hook: BeforeRequestHook) -> None: + ... @abstractmethod - def register_after_success_hook(self, hook: AfterSuccessHook): - pass + def register_after_success_hook(self, hook: AfterSuccessHook) -> None: + ... @abstractmethod - def register_after_error_hook(self, hook: AfterErrorHook): - pass + def register_after_error_hook(self, hook: AfterErrorHook) -> None: + ... diff --git a/platform/src/codat_platform/_httpx_transport.py b/platform/src/codat_platform/_httpx_transport.py new file mode 100644 index 000000000..68ec2095f --- /dev/null +++ b/platform/src/codat_platform/_httpx_transport.py @@ -0,0 +1,130 @@ +"""Adapter that routes SDK requests through a consumer-passed httpx.Client. + +Generated by pipeline/postprocess_generated.py — do not edit by hand. + +Exposes the same request() surface as the generated urllib3 RESTClientObject, +so the consumer's proxies, TLS settings, and instrumentation apply to every +request (the Speakeasy SDK behaviour for the `client` constructor kwarg). +""" + +import io +import json +import re + +from .exceptions import ApiException, ApiValueError + + +class HttpxRestResponse(io.IOBase): + + def __init__(self, resp) -> None: + self.response = resp + self.status = resp.status_code + self.reason = resp.reason_phrase + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.content + return self.data + + def getheaders(self): + """Returns the response headers (case-insensitive mapping).""" + return self.response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.response.headers.get(name, default) + + +def _to_httpx_timeout(request_timeout): + """Map the generated stack's timeout (number or (connect, read) pair) onto + an httpx.Timeout. None means: use the passed client's own default.""" + if request_timeout is None: + return None + import httpx + + if isinstance(request_timeout, (int, float)): + return httpx.Timeout(request_timeout) + connect, read = request_timeout + return httpx.Timeout(read, connect=connect) + + +class HttpxRestClient: + + def __init__(self, client) -> None: + self.client = client + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None, + ): + method = method.upper() + assert method in [ + "GET", + "HEAD", + "DELETE", + "POST", + "PUT", + "PATCH", + "OPTIONS", + ] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or [] + headers = dict(headers or {}) + + content = None + data = None + files = None + + if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]: + content_type = headers.get("Content-Type") + if not content_type or re.search("json", content_type, re.IGNORECASE): + if body is not None: + content = json.dumps(body) + elif content_type == "application/x-www-form-urlencoded": + data = dict(post_params) + elif content_type == "multipart/form-data": + # httpx must set the Content-Type itself to carry the boundary. + del headers["Content-Type"] + data = {} + files = [] + for name, value in post_params: + if isinstance(value, tuple) and len(value) == 3: + files.append((name, value)) + elif isinstance(value, dict): + data[name] = json.dumps(value) + else: + data[name] = value + elif isinstance(body, (str, bytes)): + content = body + elif content_type.startswith("text/") and isinstance(body, bool): + content = "true" if body else "false" + else: + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + + request_kwargs = {"headers": headers} + if content is not None: + request_kwargs["content"] = content + if data is not None: + request_kwargs["data"] = data + if files: + request_kwargs["files"] = files + timeout = _to_httpx_timeout(_request_timeout) + if timeout is not None: + request_kwargs["timeout"] = timeout + + resp = self.client.request(method, url, **request_kwargs) + return HttpxRestResponse(resp) diff --git a/platform/src/codat_platform/_version.py b/platform/src/codat_platform/_version.py index e5b32143a..1575c9596 100644 --- a/platform/src/codat_platform/_version.py +++ b/platform/src/codat_platform/_version.py @@ -1,12 +1,17 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Version metadata for codat-platform. + +Generated by pipeline/postprocess_generated.py — do not edit by hand. +""" + +from __future__ import annotations import importlib.metadata __title__: str = "codat-platform" -__version__: str = "5.0.1" +__version__: str = "3.0.0" __openapi_doc_version__: str = "3.0.0" -__gen_version__: str = "2.881.4" -__user_agent__: str = "speakeasy-sdk/python 5.0.1 2.881.4 3.0.0 codat-platform" +__gen_version__: str = "codat-sdk-codegen-poc-0.1.0" +__user_agent__: str = "codat-sdk/python 3.0.0 codat-sdk-codegen-poc-0.1.0 3.0.0 codat-platform" try: if __package__ is not None: diff --git a/platform/src/codat_platform/api/__init__.py b/platform/src/codat_platform/api/__init__.py new file mode 100644 index 000000000..1892519db --- /dev/null +++ b/platform/src/codat_platform/api/__init__.py @@ -0,0 +1,16 @@ +# flake8: noqa + +# import apis into api package +from codat_platform.api.companies import Companies +from codat_platform.api.connection_management import ConnectionManagement +from codat_platform.api.connections import Connections +from codat_platform.api.cors import Cors +from codat_platform.api.custom_data_type import CustomDataType +from codat_platform.api.integrations import Integrations +from codat_platform.api.push_data import PushData +from codat_platform.api.read_data import ReadData +from codat_platform.api.refresh_data import RefreshData +from codat_platform.api.settings import Settings +from codat_platform.api.supplemental_data import SupplementalData +from codat_platform.api.webhooks import Webhooks + diff --git a/platform/src/codat_platform/api/companies.py b/platform/src/codat_platform/api/companies.py new file mode 100644 index 000000000..bb7f9da42 --- /dev/null +++ b/platform/src/codat_platform/api/companies.py @@ -0,0 +1,2704 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field +from typing import Optional +from typing_extensions import Annotated +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connections import Connections +from codat_platform.models.shared.integrations import Integrations +from codat_platform.models.access_token import AccessToken +from codat_platform.models.shared.companyaccesstoken import CompanyAccessToken +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.company import Company +from codat_platform.models.shared.companyrequestbody import CompanyRequestBody, CompanyRequestBodyTypedDict +from codat_platform.models.shared.companysyncsettings import CompanySyncSettings +from codat_platform.models.shared.companyupdaterequest import CompanyUpdateRequest +from codat_platform.models.refresh_product_data_request import RefreshProductDataRequest as RefreshProductDataRequestBody +from codat_platform.models.set_company_sync_settings_request import SetCompanySyncSettingsRequest as SetCompanySyncSettingsRequestBody + +from codat_platform.api_client import ApiClient, RequestSerialized +from codat_platform.api_response import ApiResponse +from codat_platform.exceptions import ApiException +from codat_platform.models.errors import ErrorMessage, SDKError +from codat_platform.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_platform.rest import RESTResponseType +from codat_platform.types import UNSET, OptionalNullable +from codat_platform.utils.retries import RetryConfig, execute_with_retries + + +class AddProductRequestTypedDict(TypedDict): + """TypedDict variant of AddProductRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + product_identifier: Annotated[str, Field(description="Human-readable product identifier for a product.")] + + +class AddProductRequest(BaseModel): + """Request envelope for add_product.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + product_identifier: Annotated[str, Field(description="Human-readable product identifier for a product.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class CreateCompanyRequestTypedDict(TypedDict): + """TypedDict variant of CreateCompanyRequest, for dict-literal request inputs.""" + company_request_body: NotRequired[Optional[CompanyRequestBody]] + + +class CreateCompanyRequest(BaseModel): + """Request envelope for create_company.""" + company_request_body: Optional[CompanyRequestBody] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class DeleteCompanyRequestTypedDict(TypedDict): + """TypedDict variant of DeleteCompanyRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class DeleteCompanyRequest(BaseModel): + """Request envelope for delete_company.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetCompanyRequestTypedDict(TypedDict): + """TypedDict variant of GetCompanyRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class GetCompanyRequest(BaseModel): + """Request envelope for get_company.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetCompanyAccessTokenRequestTypedDict(TypedDict): + """TypedDict variant of GetCompanyAccessTokenRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class GetCompanyAccessTokenRequest(BaseModel): + """Request envelope for get_company_access_token.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetCompanySyncSettingsRequestTypedDict(TypedDict): + """TypedDict variant of GetCompanySyncSettingsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class GetCompanySyncSettingsRequest(BaseModel): + """Request envelope for get_company_sync_settings.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ListCompaniesRequestTypedDict(TypedDict): + """TypedDict variant of ListCompaniesRequest, for dict-literal request inputs.""" + page: NotRequired[Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")]] + page_size: NotRequired[Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")]] + query: NotRequired[Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")]] + order_by: NotRequired[Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")]] + tags: NotRequired[Annotated[Optional[str], Field(description="Filter companies by tags using the \"equals\" (=), \"not equals\" (!=), and \"contains\" (~) operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying).")]] + + +class ListCompaniesRequest(BaseModel): + """Request envelope for list_companies.""" + page: Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")] = 1 + page_size: Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")] = 100 + query: Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")] = None + order_by: Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")] = None + tags: Annotated[Optional[str], Field(description="Filter companies by tags using the \"equals\" (=), \"not equals\" (!=), and \"contains\" (~) operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying).")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class RefreshProductDataRequestTypedDict(TypedDict): + """TypedDict variant of RefreshProductDataRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + product_identifier: Annotated[str, Field(description="Human-readable product identifier for a product.")] + request_body: NotRequired[Annotated[Optional[RefreshProductDataRequestBody], Field(description="Optionally specify one or more data types to refresh for the given custom product. If omitted, the product's scheduled refresh is triggered as usual. When provided, each data type must be valid for the specified product.")]] + + +class RefreshProductDataRequest(BaseModel): + """Request envelope for refresh_product_data.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + product_identifier: Annotated[str, Field(description="Human-readable product identifier for a product.")] + request_body: Annotated[Optional[RefreshProductDataRequestBody], Field(description="Optionally specify one or more data types to refresh for the given custom product. If omitted, the product's scheduled refresh is triggered as usual. When provided, each data type must be valid for the specified product.")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class RemoveProductRequestTypedDict(TypedDict): + """TypedDict variant of RemoveProductRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + product_identifier: Annotated[str, Field(description="Human-readable product identifier for a product.")] + + +class RemoveProductRequest(BaseModel): + """Request envelope for remove_product.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + product_identifier: Annotated[str, Field(description="Human-readable product identifier for a product.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ReplaceCompanyRequestTypedDict(TypedDict): + """TypedDict variant of ReplaceCompanyRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + company_request_body: NotRequired[Optional[CompanyRequestBody]] + + +class ReplaceCompanyRequest(BaseModel): + """Request envelope for replace_company.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + company_request_body: Optional[CompanyRequestBody] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class SetCompanySyncSettingsRequestTypedDict(TypedDict): + """TypedDict variant of SetCompanySyncSettingsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + request_body: NotRequired[Annotated[Optional[SetCompanySyncSettingsRequestBody], Field(description="Include a `syncSetting` object for each data type. `syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them.")]] + + +class SetCompanySyncSettingsRequest(BaseModel): + """Request envelope for set_company_sync_settings.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + request_body: Annotated[Optional[SetCompanySyncSettingsRequestBody], Field(description="Include a `syncSetting` object for each data type. `syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them.")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class UpdateCompanyRequestTypedDict(TypedDict): + """TypedDict variant of UpdateCompanyRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + company_update_request: NotRequired[Optional[CompanyUpdateRequest]] + + +class UpdateCompanyRequest(BaseModel): + """Request envelope for update_company.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + company_update_request: Optional[CompanyUpdateRequest] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class Companies: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def add_product( + self, + *, + request: Union['AddProductRequest', 'AddProductRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + """Add product""" # noqa: E501 + + if isinstance(request, dict): + request = AddProductRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._add_product_serialize( + company_id=request.company_id, + product_identifier=request.product_identifier, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='add-product', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def add_product_async( + self, + *, + request: Union['AddProductRequest', 'AddProductRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.add_product( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _add_product_serialize( + self, + company_id, + product_identifier, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if product_identifier is not None: + _path_params['productIdentifier'] = product_identifier + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/companies/{companyId}/products/{productIdentifier}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def create( + self, + *, + request: Optional[Union[CompanyRequestBody, CompanyRequestBodyTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + """Create company""" # noqa: E501 + + if isinstance(request, dict): + request = CompanyRequestBody.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._create_company_serialize( + company_request_body=request, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Company", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='create-company', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def create_async( + self, + *, + request: Optional[Union[CompanyRequestBody, CompanyRequestBodyTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.create( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _create_company_serialize( + self, + company_request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if company_request_body is not None: + _body_params = company_request_body + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def delete( + self, + *, + request: Union['DeleteCompanyRequest', 'DeleteCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + """Delete a company""" # noqa: E501 + + if isinstance(request, dict): + request = DeleteCompanyRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._delete_company_serialize( + company_id=request.company_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='delete-company', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def delete_async( + self, + *, + request: Union['DeleteCompanyRequest', 'DeleteCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.delete( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _delete_company_serialize( + self, + company_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/companies/{companyId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get( + self, + *, + request: Union['GetCompanyRequest', 'GetCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + """Get company""" # noqa: E501 + + if isinstance(request, dict): + request = GetCompanyRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_company_serialize( + company_id=request.company_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Company", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-company', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_async( + self, + *, + request: Union['GetCompanyRequest', 'GetCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_company_serialize( + self, + company_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_access_token( + self, + *, + request: Union['GetCompanyAccessTokenRequest', 'GetCompanyAccessTokenRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanyAccessToken: + """Get company access token""" # noqa: E501 + + if isinstance(request, dict): + request = GetCompanyAccessTokenRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_company_access_token_serialize( + company_id=request.company_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "CompanyAccessToken", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-company-access-token', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_access_token_async( + self, + *, + request: Union['GetCompanyAccessTokenRequest', 'GetCompanyAccessTokenRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanyAccessToken: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_access_token( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_company_access_token_serialize( + self, + company_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/accessToken', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_company_sync_settings( + self, + *, + request: Union['GetCompanySyncSettingsRequest', 'GetCompanySyncSettingsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanySyncSettings: + """Get company sync settings""" # noqa: E501 + + if isinstance(request, dict): + request = GetCompanySyncSettingsRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_company_sync_settings_serialize( + company_id=request.company_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "CompanySyncSettings", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-company-syncSettings', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_company_sync_settings_async( + self, + *, + request: Union['GetCompanySyncSettingsRequest', 'GetCompanySyncSettingsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanySyncSettings: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_company_sync_settings( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_company_sync_settings_serialize( + self, + company_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/syncSettings', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def list( + self, + *, + request: Union['ListCompaniesRequest', 'ListCompaniesRequestTypedDict'] = ListCompaniesRequest(), + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Companies: + """List companies""" # noqa: E501 + + if isinstance(request, dict): + request = ListCompaniesRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._list_companies_serialize( + page=request.page, + page_size=request.page_size, + query=request.query, + order_by=request.order_by, + tags=request.tags, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Companies", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='list-companies', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def list_async( + self, + *, + request: Union['ListCompaniesRequest', 'ListCompaniesRequestTypedDict'] = ListCompaniesRequest(), + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Companies: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _list_companies_serialize( + self, + page, + page_size, + query, + order_by, + tags, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if page is not None: + + _query_params.append(('page', page)) + + if page_size is not None: + + _query_params.append(('pageSize', page_size)) + + if query is not None: + + _query_params.append(('query', query)) + + if order_by is not None: + + _query_params.append(('orderBy', order_by)) + + if tags is not None: + + _query_params.append(('tags', tags)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def refresh_product_data( + self, + *, + request: Union['RefreshProductDataRequest', 'RefreshProductDataRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + """Refresh product data""" # noqa: E501 + + if isinstance(request, dict): + request = RefreshProductDataRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._refresh_product_data_serialize( + company_id=request.company_id, + product_identifier=request.product_identifier, + request_body=request.request_body, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '202': None, + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='refresh-product-data', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def refresh_product_data_async( + self, + *, + request: Union['RefreshProductDataRequest', 'RefreshProductDataRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.refresh_product_data( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _refresh_product_data_serialize( + self, + company_id, + product_identifier, + request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if product_identifier is not None: + _path_params['productIdentifier'] = product_identifier + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if request_body is not None: + _body_params = request_body + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies/{companyId}/products/{productIdentifier}/refresh', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def remove_product( + self, + *, + request: Union['RemoveProductRequest', 'RemoveProductRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + """Remove product""" # noqa: E501 + + if isinstance(request, dict): + request = RemoveProductRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._remove_product_serialize( + company_id=request.company_id, + product_identifier=request.product_identifier, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='remove-product', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def remove_product_async( + self, + *, + request: Union['RemoveProductRequest', 'RemoveProductRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.remove_product( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _remove_product_serialize( + self, + company_id, + product_identifier, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if product_identifier is not None: + _path_params['productIdentifier'] = product_identifier + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/companies/{companyId}/products/{productIdentifier}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def replace( + self, + *, + request: Union['ReplaceCompanyRequest', 'ReplaceCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + """Replace company""" # noqa: E501 + + if isinstance(request, dict): + request = ReplaceCompanyRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._replace_company_serialize( + company_id=request.company_id, + company_request_body=request.company_request_body, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Company", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='replace-company', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def replace_async( + self, + *, + request: Union['ReplaceCompanyRequest', 'ReplaceCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.replace( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _replace_company_serialize( + self, + company_id, + company_request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if company_request_body is not None: + _body_params = company_request_body + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/companies/{companyId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def set_company_sync_settings( + self, + *, + request: Union['SetCompanySyncSettingsRequest', 'SetCompanySyncSettingsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + """Set company sync settings""" # noqa: E501 + + if isinstance(request, dict): + request = SetCompanySyncSettingsRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._set_company_sync_settings_serialize( + company_id=request.company_id, + request_body=request.request_body, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='set-company-syncSettings', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def set_company_sync_settings_async( + self, + *, + request: Union['SetCompanySyncSettingsRequest', 'SetCompanySyncSettingsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.set_company_sync_settings( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _set_company_sync_settings_serialize( + self, + company_id, + request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if request_body is not None: + _body_params = request_body + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies/{companyId}/syncSettings', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def update( + self, + *, + request: Union['UpdateCompanyRequest', 'UpdateCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + """Update company""" # noqa: E501 + + if isinstance(request, dict): + request = UpdateCompanyRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._update_company_serialize( + company_id=request.company_id, + company_update_request=request.company_update_request, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Company", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='update-company', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def update_async( + self, + *, + request: Union['UpdateCompanyRequest', 'UpdateCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.update( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _update_company_serialize( + self, + company_id, + company_update_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if company_update_request is not None: + _body_params = company_update_request + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/companies/{companyId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/platform/src/codat_platform/api/connection_management.py b/platform/src/codat_platform/api/connection_management.py new file mode 100644 index 000000000..13eccaeb0 --- /dev/null +++ b/platform/src/codat_platform/api/connection_management.py @@ -0,0 +1,259 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field +from typing_extensions import Annotated +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connections import Connections +from codat_platform.models.shared.integrations import Integrations +from codat_platform.models.shared.connectionmanagementaccesstoken import ConnectionManagementAccessToken + +from codat_platform.api_client import ApiClient, RequestSerialized +from codat_platform.api_response import ApiResponse +from codat_platform.exceptions import ApiException +from codat_platform.models.errors import ErrorMessage, SDKError +from codat_platform.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_platform.rest import RESTResponseType +from codat_platform.types import UNSET, OptionalNullable +from codat_platform.utils.retries import RetryConfig, execute_with_retries + + +class GetConnectionManagementAccessTokenRequestTypedDict(TypedDict): + """TypedDict variant of GetConnectionManagementAccessTokenRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class GetConnectionManagementAccessTokenRequest(BaseModel): + """Request envelope for get_connection_management_access_token.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ConnectionManagement: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get( + self, + *, + request: Union['GetConnectionManagementAccessTokenRequest', 'GetConnectionManagementAccessTokenRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ConnectionManagementAccessToken: + """(Deprecated) Get access token (old)""" # noqa: E501 + warnings.warn("GET /companies/{companyId}/connectionManagement/accessToken is deprecated.", DeprecationWarning) + + if isinstance(request, dict): + request = GetConnectionManagementAccessTokenRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_connection_management_access_token_serialize( + company_id=request.company_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ConnectionManagementAccessToken", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-connection-management-access-token', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_async( + self, + *, + request: Union['GetConnectionManagementAccessTokenRequest', 'GetConnectionManagementAccessTokenRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ConnectionManagementAccessToken: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_connection_management_access_token_serialize( + self, + company_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connectionManagement/accessToken', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/platform/src/codat_platform/api/connections.py b/platform/src/codat_platform/api/connections.py new file mode 100644 index 000000000..d6250b26e --- /dev/null +++ b/platform/src/codat_platform/api/connections.py @@ -0,0 +1,1416 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field +from typing import Dict, Optional +from typing_extensions import Annotated +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.integrations import Integrations +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connections import Connections +from codat_platform.models.create_connection_request import CreateConnectionRequest as CreateConnectionRequestBody +from codat_platform.models.shared.updateconnectionstatus import UpdateConnectionStatus + +from codat_platform.api_client import ApiClient, RequestSerialized +from codat_platform.api_response import ApiResponse +from codat_platform.exceptions import ApiException +from codat_platform.models.errors import ErrorMessage, SDKError +from codat_platform.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_platform.rest import RESTResponseType +from codat_platform.types import UNSET, OptionalNullable +from codat_platform.utils.retries import RetryConfig, execute_with_retries + + +class CreateConnectionRequestTypedDict(TypedDict): + """TypedDict variant of CreateConnectionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + request_body: NotRequired[Optional[CreateConnectionRequestBody]] + + +class CreateConnectionRequest(BaseModel): + """Request envelope for create_connection.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + request_body: Optional[CreateConnectionRequestBody] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class DeleteConnectionRequestTypedDict(TypedDict): + """TypedDict variant of DeleteConnectionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + + +class DeleteConnectionRequest(BaseModel): + """Request envelope for delete_connection.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetConnectionRequestTypedDict(TypedDict): + """TypedDict variant of GetConnectionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + + +class GetConnectionRequest(BaseModel): + """Request envelope for get_connection.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ListConnectionsRequestTypedDict(TypedDict): + """TypedDict variant of ListConnectionsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + page: NotRequired[Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")]] + page_size: NotRequired[Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")]] + query: NotRequired[Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")]] + order_by: NotRequired[Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")]] + + +class ListConnectionsRequest(BaseModel): + """Request envelope for list_connections.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + page: Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")] = 1 + page_size: Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")] = 100 + query: Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")] = None + order_by: Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class UnlinkConnectionRequestTypedDict(TypedDict): + """TypedDict variant of UnlinkConnectionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + update_connection_status: NotRequired[Optional[UpdateConnectionStatus]] + + +class UnlinkConnectionRequest(BaseModel): + """Request envelope for unlink_connection.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + update_connection_status: Optional[UpdateConnectionStatus] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class UpdateConnectionAuthorizationRequestTypedDict(TypedDict): + """TypedDict variant of UpdateConnectionAuthorizationRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + request_body: NotRequired[Optional[Dict[str, str]]] + + +class UpdateConnectionAuthorizationRequest(BaseModel): + """Request envelope for update_connection_authorization.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + request_body: Optional[Dict[str, str]] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class Connections: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def create( + self, + *, + request: Union['CreateConnectionRequest', 'CreateConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + """Create connection""" # noqa: E501 + + if isinstance(request, dict): + request = CreateConnectionRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._create_connection_serialize( + company_id=request.company_id, + request_body=request.request_body, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Connection", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='create-connection', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def create_async( + self, + *, + request: Union['CreateConnectionRequest', 'CreateConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.create( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _create_connection_serialize( + self, + company_id, + request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if request_body is not None: + _body_params = request_body + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies/{companyId}/connections', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def delete( + self, + *, + request: Union['DeleteConnectionRequest', 'DeleteConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + """Delete connection""" # noqa: E501 + + if isinstance(request, dict): + request = DeleteConnectionRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._delete_connection_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='delete-connection', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def delete_async( + self, + *, + request: Union['DeleteConnectionRequest', 'DeleteConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.delete( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _delete_connection_serialize( + self, + company_id, + connection_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/companies/{companyId}/connections/{connectionId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get( + self, + *, + request: Union['GetConnectionRequest', 'GetConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + """Get connection""" # noqa: E501 + + if isinstance(request, dict): + request = GetConnectionRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_connection_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Connection", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-connection', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_async( + self, + *, + request: Union['GetConnectionRequest', 'GetConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_connection_serialize( + self, + company_id, + connection_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connections/{connectionId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def list( + self, + *, + request: Union['ListConnectionsRequest', 'ListConnectionsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connections: + """List connections""" # noqa: E501 + + if isinstance(request, dict): + request = ListConnectionsRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._list_connections_serialize( + company_id=request.company_id, + page=request.page, + page_size=request.page_size, + query=request.query, + order_by=request.order_by, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Connections", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='list-connections', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def list_async( + self, + *, + request: Union['ListConnectionsRequest', 'ListConnectionsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connections: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _list_connections_serialize( + self, + company_id, + page, + page_size, + query, + order_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + if page is not None: + + _query_params.append(('page', page)) + + if page_size is not None: + + _query_params.append(('pageSize', page_size)) + + if query is not None: + + _query_params.append(('query', query)) + + if order_by is not None: + + _query_params.append(('orderBy', order_by)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connections', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def unlink( + self, + *, + request: Union['UnlinkConnectionRequest', 'UnlinkConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + """Unlink connection""" # noqa: E501 + + if isinstance(request, dict): + request = UnlinkConnectionRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._unlink_connection_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + update_connection_status=request.update_connection_status, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Connection", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='unlink-connection', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def unlink_async( + self, + *, + request: Union['UnlinkConnectionRequest', 'UnlinkConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.unlink( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _unlink_connection_serialize( + self, + company_id, + connection_id, + update_connection_status, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if update_connection_status is not None: + _body_params = update_connection_status + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/companies/{companyId}/connections/{connectionId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def update_authorization( + self, + *, + request: Union['UpdateConnectionAuthorizationRequest', 'UpdateConnectionAuthorizationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + """Update authorization""" # noqa: E501 + + if isinstance(request, dict): + request = UpdateConnectionAuthorizationRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._update_connection_authorization_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + request_body=request.request_body, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Connection", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='update-connection-authorization', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def update_authorization_async( + self, + *, + request: Union['UpdateConnectionAuthorizationRequest', 'UpdateConnectionAuthorizationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.update_authorization( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _update_connection_authorization_serialize( + self, + company_id, + connection_id, + request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if request_body is not None: + _body_params = request_body + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/companies/{companyId}/connections/{connectionId}/authorization', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/platform/src/codat_platform/api/cors.py b/platform/src/codat_platform/api/cors.py new file mode 100644 index 000000000..2953baae5 --- /dev/null +++ b/platform/src/codat_platform/api/cors.py @@ -0,0 +1,455 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from typing import Optional +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connections import Connections +from codat_platform.models.shared.integrations import Integrations +from codat_platform.models.shared.connectionmanagementallowedorigins import ConnectionManagementAllowedOrigins, ConnectionManagementAllowedOriginsTypedDict + +from codat_platform.api_client import ApiClient, RequestSerialized +from codat_platform.api_response import ApiResponse +from codat_platform.exceptions import ApiException +from codat_platform.models.errors import ErrorMessage, SDKError +from codat_platform.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_platform.rest import RESTResponseType +from codat_platform.types import UNSET, OptionalNullable +from codat_platform.utils.retries import RetryConfig, execute_with_retries + + +class SetConnectionManagementCorsSettingsRequestTypedDict(TypedDict): + """TypedDict variant of SetConnectionManagementCorsSettingsRequest, for dict-literal request inputs.""" + connection_management_allowed_origins: NotRequired[Optional[ConnectionManagementAllowedOrigins]] + + +class SetConnectionManagementCorsSettingsRequest(BaseModel): + """Request envelope for set_connection_management_cors_settings.""" + connection_management_allowed_origins: Optional[ConnectionManagementAllowedOrigins] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class Cors: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ConnectionManagementAllowedOrigins: + """(Deprecated) Get CORS settings (old)""" # noqa: E501 + warnings.warn("GET /connectionManagement/corsSettings is deprecated.", DeprecationWarning) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_connection_management_cors_settings_serialize( + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ConnectionManagementAllowedOrigins", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-connection-management-cors-settings', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_async( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ConnectionManagementAllowedOrigins: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get( + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_connection_management_cors_settings_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/connectionManagement/corsSettings', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def set( + self, + *, + request: Optional[Union[ConnectionManagementAllowedOrigins, ConnectionManagementAllowedOriginsTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ConnectionManagementAllowedOrigins: + """(Deprecated) Set CORS settings (old)""" # noqa: E501 + warnings.warn("POST /connectionManagement/corsSettings is deprecated.", DeprecationWarning) + + if isinstance(request, dict): + request = ConnectionManagementAllowedOrigins.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._set_connection_management_cors_settings_serialize( + connection_management_allowed_origins=request, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ConnectionManagementAllowedOrigins", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='set-connection-management-cors-settings', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def set_async( + self, + *, + request: Optional[Union[ConnectionManagementAllowedOrigins, ConnectionManagementAllowedOriginsTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ConnectionManagementAllowedOrigins: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.set( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _set_connection_management_cors_settings_serialize( + self, + connection_management_allowed_origins, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if connection_management_allowed_origins is not None: + _body_params = connection_management_allowed_origins + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/connectionManagement/corsSettings', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/platform/src/codat_platform/api/custom_data_type.py b/platform/src/codat_platform/api/custom_data_type.py new file mode 100644 index 000000000..2007f7280 --- /dev/null +++ b/platform/src/codat_platform/api/custom_data_type.py @@ -0,0 +1,961 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field, field_validator +from typing import Optional +from typing_extensions import Annotated +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connections import Connections +from codat_platform.models.shared.integrations import Integrations +from codat_platform.models.shared.customdatatypeconfiguration import CustomDataTypeConfiguration +from codat_platform.models.shared.customdatatyperecords import CustomDataTypeRecords +from codat_platform.models.shared.pulloperation import PullOperation + +from codat_platform.api_client import ApiClient, RequestSerialized +from codat_platform.api_response import ApiResponse +from codat_platform.exceptions import ApiException +from codat_platform.models.errors import ErrorMessage, SDKError +from codat_platform.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_platform.rest import RESTResponseType +from codat_platform.types import UNSET, OptionalNullable +from codat_platform.utils.retries import RetryConfig, execute_with_retries + + +class ConfigureCustomDataTypeRequestTypedDict(TypedDict): + """TypedDict variant of ConfigureCustomDataTypeRequest, for dict-literal request inputs.""" + platform_key: Annotated[str, Field(description="A unique 4-letter key to represent a platform in each integration.")] + custom_data_identifier: Annotated[str, Field(description="Unique identifier for a custom data type.")] + custom_data_type_configuration: NotRequired[Annotated[Optional[CustomDataTypeConfiguration], Field(description="Custom data type configuration for the specified platform.")]] + + +class ConfigureCustomDataTypeRequest(BaseModel): + """Request envelope for configure_custom_data_type.""" + platform_key: Annotated[str, Field(description="A unique 4-letter key to represent a platform in each integration.")] + custom_data_identifier: Annotated[str, Field(description="Unique identifier for a custom data type.")] + custom_data_type_configuration: Annotated[Optional[CustomDataTypeConfiguration], Field(description="Custom data type configuration for the specified platform.")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetCustomDataTypeConfigurationRequestTypedDict(TypedDict): + """TypedDict variant of GetCustomDataTypeConfigurationRequest, for dict-literal request inputs.""" + platform_key: Annotated[str, Field(description="A unique 4-letter key to represent a platform in each integration.")] + custom_data_identifier: Annotated[str, Field(description="Unique identifier for a custom data type.")] + + +class GetCustomDataTypeConfigurationRequest(BaseModel): + """Request envelope for get_custom_data_type_configuration.""" + platform_key: Annotated[str, Field(description="A unique 4-letter key to represent a platform in each integration.")] + custom_data_identifier: Annotated[str, Field(description="Unique identifier for a custom data type.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ListCustomDataTypeRecordsRequestTypedDict(TypedDict): + """TypedDict variant of ListCustomDataTypeRecordsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + custom_data_identifier: Annotated[str, Field(description="Unique identifier for a custom data type.")] + page: NotRequired[Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")]] + page_size: NotRequired[Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")]] + + +class ListCustomDataTypeRecordsRequest(BaseModel): + """Request envelope for list_custom_data_type_records.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + custom_data_identifier: Annotated[str, Field(description="Unique identifier for a custom data type.")] + page: Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")] = 1 + page_size: Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")] = 100 + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class RefreshCustomDataTypeRequestTypedDict(TypedDict): + """TypedDict variant of RefreshCustomDataTypeRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + custom_data_identifier: Annotated[str, Field(description="Unique identifier for a custom data type.")] + + +class RefreshCustomDataTypeRequest(BaseModel): + """Request envelope for refresh_custom_data_type.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + custom_data_identifier: Annotated[str, Field(description="Unique identifier for a custom data type.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class CustomDataType: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def configure( + self, + *, + request: Union['ConfigureCustomDataTypeRequest', 'ConfigureCustomDataTypeRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CustomDataTypeConfiguration: + """Configure custom data type""" # noqa: E501 + + if isinstance(request, dict): + request = ConfigureCustomDataTypeRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._configure_custom_data_type_serialize( + platform_key=request.platform_key, + custom_data_identifier=request.custom_data_identifier, + custom_data_type_configuration=request.custom_data_type_configuration, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "CustomDataTypeConfiguration", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='configure-custom-data-type', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def configure_async( + self, + *, + request: Union['ConfigureCustomDataTypeRequest', 'ConfigureCustomDataTypeRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CustomDataTypeConfiguration: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.configure( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _configure_custom_data_type_serialize( + self, + platform_key, + custom_data_identifier, + custom_data_type_configuration, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if platform_key is not None: + _path_params['platformKey'] = platform_key + if custom_data_identifier is not None: + _path_params['customDataIdentifier'] = custom_data_identifier + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if custom_data_type_configuration is not None: + _body_params = custom_data_type_configuration + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/integrations/{platformKey}/dataTypes/custom/{customDataIdentifier}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_configuration( + self, + *, + request: Union['GetCustomDataTypeConfigurationRequest', 'GetCustomDataTypeConfigurationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CustomDataTypeRecords: + """Get custom data configuration""" # noqa: E501 + + if isinstance(request, dict): + request = GetCustomDataTypeConfigurationRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_custom_data_type_configuration_serialize( + platform_key=request.platform_key, + custom_data_identifier=request.custom_data_identifier, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "CustomDataTypeRecords", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-custom-data-type-configuration', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_configuration_async( + self, + *, + request: Union['GetCustomDataTypeConfigurationRequest', 'GetCustomDataTypeConfigurationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CustomDataTypeRecords: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_configuration( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_custom_data_type_configuration_serialize( + self, + platform_key, + custom_data_identifier, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if platform_key is not None: + _path_params['platformKey'] = platform_key + if custom_data_identifier is not None: + _path_params['customDataIdentifier'] = custom_data_identifier + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/integrations/{platformKey}/dataTypes/custom/{customDataIdentifier}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def list( + self, + *, + request: Union['ListCustomDataTypeRecordsRequest', 'ListCustomDataTypeRecordsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CustomDataTypeRecords: + """List custom data type records""" # noqa: E501 + + if isinstance(request, dict): + request = ListCustomDataTypeRecordsRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._list_custom_data_type_records_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + custom_data_identifier=request.custom_data_identifier, + page=request.page, + page_size=request.page_size, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "CustomDataTypeRecords", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '451': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='list-custom-data-type-records', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def list_async( + self, + *, + request: Union['ListCustomDataTypeRecordsRequest', 'ListCustomDataTypeRecordsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CustomDataTypeRecords: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _list_custom_data_type_records_serialize( + self, + company_id, + connection_id, + custom_data_identifier, + page, + page_size, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + if custom_data_identifier is not None: + _path_params['customDataIdentifier'] = custom_data_identifier + # process the query parameters + if page is not None: + + _query_params.append(('page', page)) + + if page_size is not None: + + _query_params.append(('pageSize', page_size)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connections/{connectionId}/data/custom/{customDataIdentifier}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def refresh( + self, + *, + request: Union['RefreshCustomDataTypeRequest', 'RefreshCustomDataTypeRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperation: + """Refresh custom data type""" # noqa: E501 + + if isinstance(request, dict): + request = RefreshCustomDataTypeRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._refresh_custom_data_type_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + custom_data_identifier=request.custom_data_identifier, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PullOperation", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '451': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='refresh-custom-data-type', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def refresh_async( + self, + *, + request: Union['RefreshCustomDataTypeRequest', 'RefreshCustomDataTypeRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperation: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.refresh( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _refresh_custom_data_type_serialize( + self, + company_id, + connection_id, + custom_data_identifier, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + if custom_data_identifier is not None: + _path_params['customDataIdentifier'] = custom_data_identifier + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies/{companyId}/connections/{connectionId}/data/queue/custom/{customDataIdentifier}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/platform/src/codat_platform/api/integrations.py b/platform/src/codat_platform/api/integrations.py new file mode 100644 index 000000000..f57a8b118 --- /dev/null +++ b/platform/src/codat_platform/api/integrations.py @@ -0,0 +1,704 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field, field_validator +from typing import Optional +from typing_extensions import Annotated +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connections import Connections +from codat_platform.models.shared.branding import Branding +from codat_platform.models.shared.integration import Integration +from codat_platform.models.shared.integrations import Integrations + +from codat_platform.api_client import ApiClient, RequestSerialized +from codat_platform.api_response import ApiResponse +from codat_platform.exceptions import ApiException +from codat_platform.models.errors import ErrorMessage, SDKError +from codat_platform.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_platform.rest import RESTResponseType +from codat_platform.types import UNSET, OptionalNullable +from codat_platform.utils.retries import RetryConfig, execute_with_retries + + +class GetIntegrationRequestTypedDict(TypedDict): + """TypedDict variant of GetIntegrationRequest, for dict-literal request inputs.""" + platform_key: Annotated[str, Field(description="A unique 4-letter key to represent a platform in each integration.")] + + +class GetIntegrationRequest(BaseModel): + """Request envelope for get_integration.""" + platform_key: Annotated[str, Field(description="A unique 4-letter key to represent a platform in each integration.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetIntegrationsBrandingRequestTypedDict(TypedDict): + """TypedDict variant of GetIntegrationsBrandingRequest, for dict-literal request inputs.""" + platform_key: Annotated[str, Field(description="A unique 4-letter key to represent a platform in each integration.")] + + +class GetIntegrationsBrandingRequest(BaseModel): + """Request envelope for get_integrations_branding.""" + platform_key: Annotated[str, Field(description="A unique 4-letter key to represent a platform in each integration.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ListIntegrationsRequestTypedDict(TypedDict): + """TypedDict variant of ListIntegrationsRequest, for dict-literal request inputs.""" + page: NotRequired[Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")]] + page_size: NotRequired[Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")]] + query: NotRequired[Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")]] + order_by: NotRequired[Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")]] + + +class ListIntegrationsRequest(BaseModel): + """Request envelope for list_integrations.""" + page: Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")] = 1 + page_size: Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")] = 100 + query: Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")] = None + order_by: Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class Integrations: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get( + self, + *, + request: Union['GetIntegrationRequest', 'GetIntegrationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Integration: + """Get integration""" # noqa: E501 + + if isinstance(request, dict): + request = GetIntegrationRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_integration_serialize( + platform_key=request.platform_key, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Integration", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-integration', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_async( + self, + *, + request: Union['GetIntegrationRequest', 'GetIntegrationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Integration: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_integration_serialize( + self, + platform_key, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if platform_key is not None: + _path_params['platformKey'] = platform_key + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/integrations/{platformKey}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_branding( + self, + *, + request: Union['GetIntegrationsBrandingRequest', 'GetIntegrationsBrandingRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Branding: + """Get branding""" # noqa: E501 + + if isinstance(request, dict): + request = GetIntegrationsBrandingRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_integrations_branding_serialize( + platform_key=request.platform_key, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Branding", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-integrations-branding', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_branding_async( + self, + *, + request: Union['GetIntegrationsBrandingRequest', 'GetIntegrationsBrandingRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Branding: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_branding( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_integrations_branding_serialize( + self, + platform_key, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if platform_key is not None: + _path_params['platformKey'] = platform_key + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/integrations/{platformKey}/branding', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def list( + self, + *, + request: Union['ListIntegrationsRequest', 'ListIntegrationsRequestTypedDict'] = ListIntegrationsRequest(), + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Integrations: + """List integrations""" # noqa: E501 + + if isinstance(request, dict): + request = ListIntegrationsRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._list_integrations_serialize( + page=request.page, + page_size=request.page_size, + query=request.query, + order_by=request.order_by, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Integrations", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='list-integrations', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def list_async( + self, + *, + request: Union['ListIntegrationsRequest', 'ListIntegrationsRequestTypedDict'] = ListIntegrationsRequest(), + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Integrations: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _list_integrations_serialize( + self, + page, + page_size, + query, + order_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if page is not None: + + _query_params.append(('page', page)) + + if page_size is not None: + + _query_params.append(('pageSize', page_size)) + + if query is not None: + + _query_params.append(('query', query)) + + if order_by is not None: + + _query_params.append(('orderBy', order_by)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/integrations', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/platform/src/codat_platform/api/push_data.py b/platform/src/codat_platform/api/push_data.py new file mode 100644 index 000000000..464a1a5a5 --- /dev/null +++ b/platform/src/codat_platform/api/push_data.py @@ -0,0 +1,732 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field, field_validator +from typing import Optional +from typing_extensions import Annotated +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connections import Connections +from codat_platform.models.shared.integrations import Integrations +from codat_platform.models.shared.datatype import DataType +from codat_platform.models.shared.pushoperation import PushOperation +from codat_platform.models.shared.pushoperations import PushOperations +from codat_platform.models.shared.pushoption import PushOption + +from codat_platform.api_client import ApiClient, RequestSerialized +from codat_platform.api_response import ApiResponse +from codat_platform.exceptions import ApiException +from codat_platform.models.errors import ErrorMessage, SDKError +from codat_platform.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_platform.rest import RESTResponseType +from codat_platform.types import UNSET, OptionalNullable +from codat_platform.utils.retries import RetryConfig, execute_with_retries + + +from codat_platform.models._compat.schema_datatype import SchemaDataType +class GetCompanyPushHistoryRequestTypedDict(TypedDict): + """TypedDict variant of GetCompanyPushHistoryRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + page: NotRequired[Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")]] + page_size: NotRequired[Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")]] + query: NotRequired[Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")]] + order_by: NotRequired[Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")]] + + +class GetCompanyPushHistoryRequest(BaseModel): + """Request envelope for get_company_push_history.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + page: Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")] = 1 + page_size: Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")] = 100 + query: Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")] = None + order_by: Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetCreateUpdateModelOptionsByDataTypeRequestTypedDict(TypedDict): + """TypedDict variant of GetCreateUpdateModelOptionsByDataTypeRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + data_type: Annotated[SchemaDataType, Field(description="The key of a Codat data type.")] + + +class GetCreateUpdateModelOptionsByDataTypeRequest(BaseModel): + """Request envelope for get_create_update_model_options_by_data_type.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + data_type: Annotated[SchemaDataType, Field(description="The key of a Codat data type.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetPushOperationRequestTypedDict(TypedDict): + """TypedDict variant of GetPushOperationRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + push_operation_key: Annotated[str, Field(description="Push operation key.")] + + +class GetPushOperationRequest(BaseModel): + """Request envelope for get_push_operation.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + push_operation_key: Annotated[str, Field(description="Push operation key.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class PushData: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def list_operations( + self, + *, + request: Union['GetCompanyPushHistoryRequest', 'GetCompanyPushHistoryRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOperations: + """List push operations""" # noqa: E501 + + if isinstance(request, dict): + request = GetCompanyPushHistoryRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_company_push_history_serialize( + company_id=request.company_id, + page=request.page, + page_size=request.page_size, + query=request.query, + order_by=request.order_by, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PushOperations", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-company-push-history', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def list_operations_async( + self, + *, + request: Union['GetCompanyPushHistoryRequest', 'GetCompanyPushHistoryRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOperations: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list_operations( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_company_push_history_serialize( + self, + company_id, + page, + page_size, + query, + order_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + if page is not None: + + _query_params.append(('page', page)) + + if page_size is not None: + + _query_params.append(('pageSize', page_size)) + + if query is not None: + + _query_params.append(('query', query)) + + if order_by is not None: + + _query_params.append(('orderBy', order_by)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/push', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_model_options( + self, + *, + request: Union['GetCreateUpdateModelOptionsByDataTypeRequest', 'GetCreateUpdateModelOptionsByDataTypeRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOption: + """Get push options""" # noqa: E501 + + if isinstance(request, dict): + request = GetCreateUpdateModelOptionsByDataTypeRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_create_update_model_options_by_data_type_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + data_type=request.data_type, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PushOption", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-create-update-model-options-by-data-type', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_model_options_async( + self, + *, + request: Union['GetCreateUpdateModelOptionsByDataTypeRequest', 'GetCreateUpdateModelOptionsByDataTypeRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOption: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_model_options( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_create_update_model_options_by_data_type_serialize( + self, + company_id, + connection_id, + data_type, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + if data_type is not None: + _path_params['dataType'] = data_type + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connections/{connectionId}/options/{dataType}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_operation( + self, + *, + request: Union['GetPushOperationRequest', 'GetPushOperationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOperation: + """Get push operation""" # noqa: E501 + + if isinstance(request, dict): + request = GetPushOperationRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_push_operation_serialize( + company_id=request.company_id, + push_operation_key=request.push_operation_key, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PushOperation", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-push-operation', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_operation_async( + self, + *, + request: Union['GetPushOperationRequest', 'GetPushOperationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOperation: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_operation( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_push_operation_serialize( + self, + company_id, + push_operation_key, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if push_operation_key is not None: + _path_params['pushOperationKey'] = push_operation_key + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/push/{pushOperationKey}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/platform/src/codat_platform/api/read_data.py b/platform/src/codat_platform/api/read_data.py new file mode 100644 index 000000000..e398780d3 --- /dev/null +++ b/platform/src/codat_platform/api/read_data.py @@ -0,0 +1,264 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field +from typing_extensions import Annotated +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connections import Connections +from codat_platform.models.shared.integrations import Integrations +from codat_platform.models.shared.validationresult import ValidationResult + +from codat_platform.api_client import ApiClient, RequestSerialized +from codat_platform.api_response import ApiResponse +from codat_platform.exceptions import ApiException +from codat_platform.models.errors import ErrorMessage, SDKError +from codat_platform.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_platform.rest import RESTResponseType +from codat_platform.types import UNSET, OptionalNullable +from codat_platform.utils.retries import RetryConfig, execute_with_retries + + +class GetReadValidationResultsRequestTypedDict(TypedDict): + """TypedDict variant of GetReadValidationResultsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + dataset_id: Annotated[str, Field(description="Unique identifier for the dataset that completed its sync.")] + + +class GetReadValidationResultsRequest(BaseModel): + """Request envelope for get_read_validation_results.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + dataset_id: Annotated[str, Field(description="Unique identifier for the dataset that completed its sync.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ReadData: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_validation_results( + self, + *, + request: Union['GetReadValidationResultsRequest', 'GetReadValidationResultsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ValidationResult: + """Get validation results""" # noqa: E501 + + if isinstance(request, dict): + request = GetReadValidationResultsRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_read_validation_results_serialize( + company_id=request.company_id, + dataset_id=request.dataset_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ValidationResult", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-read-validation-results', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_validation_results_async( + self, + *, + request: Union['GetReadValidationResultsRequest', 'GetReadValidationResultsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ValidationResult: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_validation_results( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_read_validation_results_serialize( + self, + company_id, + dataset_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if dataset_id is not None: + _path_params['datasetId'] = dataset_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/sync/{datasetId}/validation', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/platform/src/codat_platform/api/refresh_data.py b/platform/src/codat_platform/api/refresh_data.py new file mode 100644 index 000000000..0eb29f8c9 --- /dev/null +++ b/platform/src/codat_platform/api/refresh_data.py @@ -0,0 +1,1154 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field, field_validator +from typing import Optional +from typing_extensions import Annotated +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connections import Connections +from codat_platform.models.shared.integrations import Integrations +from codat_platform.models.shared.datastatuses import DataStatuses +from codat_platform.models.shared.datatype import DataType +from codat_platform.models.shared.pulloperation import PullOperation +from codat_platform.models.shared.pulloperations import PullOperations + +from codat_platform.api_client import ApiClient, RequestSerialized +from codat_platform.api_response import ApiResponse +from codat_platform.exceptions import ApiException +from codat_platform.models.errors import ErrorMessage, SDKError +from codat_platform.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_platform.rest import RESTResponseType +from codat_platform.types import UNSET, OptionalNullable +from codat_platform.utils.retries import RetryConfig, execute_with_retries + + +from codat_platform.models._compat.schema_datatype import SchemaDataType +class GetCompanyDataStatusRequestTypedDict(TypedDict): + """TypedDict variant of GetCompanyDataStatusRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class GetCompanyDataStatusRequest(BaseModel): + """Request envelope for get_company_data_status.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetPullOperationRequestTypedDict(TypedDict): + """TypedDict variant of GetPullOperationRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + dataset_id: Annotated[str, Field(description="Unique identifier for the dataset that completed its sync.")] + + +class GetPullOperationRequest(BaseModel): + """Request envelope for get_pull_operation.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + dataset_id: Annotated[str, Field(description="Unique identifier for the dataset that completed its sync.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ListPullOperationsRequestTypedDict(TypedDict): + """TypedDict variant of ListPullOperationsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + page: NotRequired[Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")]] + page_size: NotRequired[Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")]] + query: NotRequired[Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")]] + order_by: NotRequired[Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")]] + + +class ListPullOperationsRequest(BaseModel): + """Request envelope for list_pull_operations.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + page: Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")] = 1 + page_size: Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")] = 100 + query: Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")] = None + order_by: Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class RefreshCompanyDataRequestTypedDict(TypedDict): + """TypedDict variant of RefreshCompanyDataRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class RefreshCompanyDataRequest(BaseModel): + """Request envelope for refresh_company_data.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class RefreshDataTypeRequestTypedDict(TypedDict): + """TypedDict variant of RefreshDataTypeRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + data_type: Annotated[SchemaDataType, Field(description="The key of a Codat data type.")] + connection_id: NotRequired[Annotated[Optional[str], Field(description="Optionally, provide a data connection id to only queue pull operations on that connection.")]] + + +class RefreshDataTypeRequest(BaseModel): + """Request envelope for refresh_data_type.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + data_type: Annotated[SchemaDataType, Field(description="The key of a Codat data type.")] + connection_id: Annotated[Optional[str], Field(description="Optionally, provide a data connection id to only queue pull operations on that connection.")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class RefreshData: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get( + self, + *, + request: Union['GetCompanyDataStatusRequest', 'GetCompanyDataStatusRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> DataStatuses: + """Get data status""" # noqa: E501 + + if isinstance(request, dict): + request = GetCompanyDataStatusRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_company_data_status_serialize( + company_id=request.company_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DataStatuses", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-company-data-status', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_async( + self, + *, + request: Union['GetCompanyDataStatusRequest', 'GetCompanyDataStatusRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> DataStatuses: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_company_data_status_serialize( + self, + company_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/dataStatus', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_pull_operation( + self, + *, + request: Union['GetPullOperationRequest', 'GetPullOperationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperation: + """Get pull operation""" # noqa: E501 + + if isinstance(request, dict): + request = GetPullOperationRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_pull_operation_serialize( + company_id=request.company_id, + dataset_id=request.dataset_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PullOperation", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-pull-operation', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_pull_operation_async( + self, + *, + request: Union['GetPullOperationRequest', 'GetPullOperationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperation: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_pull_operation( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_pull_operation_serialize( + self, + company_id, + dataset_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if dataset_id is not None: + _path_params['datasetId'] = dataset_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/data/history/{datasetId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def list_pull_operations( + self, + *, + request: Union['ListPullOperationsRequest', 'ListPullOperationsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperations: + """List pull operations""" # noqa: E501 + + if isinstance(request, dict): + request = ListPullOperationsRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._list_pull_operations_serialize( + company_id=request.company_id, + page=request.page, + page_size=request.page_size, + query=request.query, + order_by=request.order_by, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PullOperations", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='list-pull-operations', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def list_pull_operations_async( + self, + *, + request: Union['ListPullOperationsRequest', 'ListPullOperationsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperations: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list_pull_operations( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _list_pull_operations_serialize( + self, + company_id, + page, + page_size, + query, + order_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + if page is not None: + + _query_params.append(('page', page)) + + if page_size is not None: + + _query_params.append(('pageSize', page_size)) + + if query is not None: + + _query_params.append(('query', query)) + + if order_by is not None: + + _query_params.append(('orderBy', order_by)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/data/history', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def all( + self, + *, + request: Union['RefreshCompanyDataRequest', 'RefreshCompanyDataRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + """Refresh all data""" # noqa: E501 + + if isinstance(request, dict): + request = RefreshCompanyDataRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._refresh_company_data_serialize( + company_id=request.company_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='refresh-company-data', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def all_async( + self, + *, + request: Union['RefreshCompanyDataRequest', 'RefreshCompanyDataRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.all( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _refresh_company_data_serialize( + self, + company_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies/{companyId}/data/all', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def by_data_type( + self, + *, + request: Union['RefreshDataTypeRequest', 'RefreshDataTypeRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperation: + """Refresh data type""" # noqa: E501 + + if isinstance(request, dict): + request = RefreshDataTypeRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._refresh_data_type_serialize( + company_id=request.company_id, + data_type=request.data_type, + connection_id=request.connection_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PullOperation", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='refresh-data-type', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def by_data_type_async( + self, + *, + request: Union['RefreshDataTypeRequest', 'RefreshDataTypeRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperation: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.by_data_type( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _refresh_data_type_serialize( + self, + company_id, + data_type, + connection_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if data_type is not None: + _path_params['dataType'] = data_type + # process the query parameters + if connection_id is not None: + + _query_params.append(('connectionId', connection_id)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies/{companyId}/data/queue/{dataType}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/platform/src/codat_platform/api/settings.py b/platform/src/codat_platform/api/settings.py new file mode 100644 index 000000000..bcf2500aa --- /dev/null +++ b/platform/src/codat_platform/api/settings.py @@ -0,0 +1,1897 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field +from typing import Optional +from typing_extensions import Annotated +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connections import Connections +from codat_platform.models.shared.integrations import Integrations +from codat_platform.models.shared.apikeydetails import APIKeyDetails +from codat_platform.models.shared.apikeys import APIKeys +from codat_platform.models.shared.connectionmanagementallowedorigins import ConnectionManagementAllowedOrigins, ConnectionManagementAllowedOriginsTypedDict +from codat_platform.models.shared.createapikey import CreateAPIKey, CreateAPIKeyTypedDict +from codat_platform.models.shared.errormessage import ErrorMessage +from codat_platform.models.shared.profile import Profile, ProfileTypedDict +from codat_platform.models.shared.syncsettings import SyncSettings +from codat_platform.models.update_profile_sync_settings_request import UpdateProfileSyncSettingsRequest, UpdateProfileSyncSettingsRequestTypedDict +# Speakeasy compat alias — body class shares its name with the +# request wrapper, so we expose it under the Speakeasy-style `Body` name. +UpdateProfileSyncSettingsRequestBody = UpdateProfileSyncSettingsRequest +UpdateProfileSyncSettingsRequestBodyTypedDict = UpdateProfileSyncSettingsRequestTypedDict + +from codat_platform.api_client import ApiClient, RequestSerialized +from codat_platform.api_response import ApiResponse +from codat_platform.exceptions import ApiException +from codat_platform.models.errors import ErrorMessage, SDKError +from codat_platform.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_platform.rest import RESTResponseType +from codat_platform.types import UNSET, OptionalNullable +from codat_platform.utils.retries import RetryConfig, execute_with_retries + + +class CreateApiKeyRequestTypedDict(TypedDict): + """TypedDict variant of CreateApiKeyRequest, for dict-literal request inputs.""" + create_api_key: NotRequired[Optional[CreateAPIKey]] + + +class CreateApiKeyRequest(BaseModel): + """Request envelope for create_api_key.""" + create_api_key: Optional[CreateAPIKey] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class DeleteAPIKeyRequestTypedDict(TypedDict): + """TypedDict variant of DeleteAPIKeyRequest, for dict-literal request inputs.""" + api_key_id: Annotated[str, Field(description="Unique identifier for api key.")] + + +class DeleteAPIKeyRequest(BaseModel): + """Request envelope for delete_api_key.""" + api_key_id: Annotated[str, Field(description="Unique identifier for api key.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class SetCorsSettingsRequestTypedDict(TypedDict): + """TypedDict variant of SetCorsSettingsRequest, for dict-literal request inputs.""" + connection_management_allowed_origins: NotRequired[Optional[ConnectionManagementAllowedOrigins]] + + +class SetCorsSettingsRequest(BaseModel): + """Request envelope for set_cors_settings.""" + connection_management_allowed_origins: Optional[ConnectionManagementAllowedOrigins] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class UpdateProfileRequestTypedDict(TypedDict): + """TypedDict variant of UpdateProfileRequest, for dict-literal request inputs.""" + profile: NotRequired[Annotated[Optional[Profile], Field(description="All fields should be included when updating your profile.")]] + + +class UpdateProfileRequest(BaseModel): + """Request envelope for update_profile.""" + profile: Annotated[Optional[Profile], Field(description="All fields should be included when updating your profile.")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class UpdateProfileSyncSettingsRequestTypedDict(TypedDict): + """TypedDict variant of UpdateProfileSyncSettingsRequest, for dict-literal request inputs.""" + update_profile_sync_settings_request: NotRequired[Annotated[Optional[UpdateProfileSyncSettingsRequest], Field(description="Include a `syncSetting` object for each data type. `syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them.")]] + + +class UpdateProfileSyncSettingsRequest(BaseModel): + """Request envelope for update_profile_sync_settings.""" + update_profile_sync_settings_request: Annotated[Optional[UpdateProfileSyncSettingsRequest], Field(description="Include a `syncSetting` object for each data type. `syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them.")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class Settings: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def create_api_key( + self, + *, + request: Optional[Union[CreateAPIKey, CreateAPIKeyTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> APIKeyDetails: + """Create API key""" # noqa: E501 + + if isinstance(request, dict): + request = CreateAPIKey.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._create_api_key_serialize( + create_api_key=request, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "APIKeyDetails", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '409': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='create-api-key', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def create_api_key_async( + self, + *, + request: Optional[Union[CreateAPIKey, CreateAPIKeyTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> APIKeyDetails: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.create_api_key( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _create_api_key_serialize( + self, + create_api_key, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if create_api_key is not None: + _body_params = create_api_key + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/apiKeys', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def delete_api_key( + self, + *, + request: Union['DeleteAPIKeyRequest', 'DeleteAPIKeyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ErrorMessage: + """Delete API key""" # noqa: E501 + + if isinstance(request, dict): + request = DeleteAPIKeyRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._delete_api_key_serialize( + api_key_id=request.api_key_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='delete-api-key', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def delete_api_key_async( + self, + *, + request: Union['DeleteAPIKeyRequest', 'DeleteAPIKeyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ErrorMessage: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.delete_api_key( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _delete_api_key_serialize( + self, + api_key_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if api_key_id is not None: + _path_params['apiKeyId'] = api_key_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/apiKeys/{apiKeyId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ConnectionManagementAllowedOrigins: + """Get CORS settings""" # noqa: E501 + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_cors_settings_serialize( + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ConnectionManagementAllowedOrigins", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-cors-settings', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_async( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ConnectionManagementAllowedOrigins: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get( + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_cors_settings_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/corsSettings', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_profile( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Profile: + """Get profile""" # noqa: E501 + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_profile_serialize( + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Profile", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-profile', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_profile_async( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Profile: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_profile( + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_profile_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/profile', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_sync_settings( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> SyncSettings: + """Get sync settings""" # noqa: E501 + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_profile_sync_settings_serialize( + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "SyncSettings", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-profile-syncSettings', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_sync_settings_async( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> SyncSettings: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_sync_settings( + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_profile_sync_settings_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/profile/syncSettings', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def list_api_keys( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> APIKeys: + """List API keys""" # noqa: E501 + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._list_api_keys_serialize( + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "APIKeys", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='list-api-keys', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def list_api_keys_async( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> APIKeys: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list_api_keys( + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _list_api_keys_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/apiKeys', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def set( + self, + *, + request: Optional[Union[ConnectionManagementAllowedOrigins, ConnectionManagementAllowedOriginsTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ConnectionManagementAllowedOrigins: + """Set CORS settings""" # noqa: E501 + + if isinstance(request, dict): + request = ConnectionManagementAllowedOrigins.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._set_cors_settings_serialize( + connection_management_allowed_origins=request, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ConnectionManagementAllowedOrigins", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='set-cors-settings', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def set_async( + self, + *, + request: Optional[Union[ConnectionManagementAllowedOrigins, ConnectionManagementAllowedOriginsTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> ConnectionManagementAllowedOrigins: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.set( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _set_cors_settings_serialize( + self, + connection_management_allowed_origins, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if connection_management_allowed_origins is not None: + _body_params = connection_management_allowed_origins + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/corsSettings', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def update_profile( + self, + *, + request: Optional[Union[Profile, ProfileTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Profile: + """Update profile""" # noqa: E501 + + if isinstance(request, dict): + request = Profile.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._update_profile_serialize( + profile=request, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Profile", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='update-profile', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def update_profile_async( + self, + *, + request: Optional[Union[Profile, ProfileTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Profile: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.update_profile( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _update_profile_serialize( + self, + profile, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if profile is not None: + _body_params = profile + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/profile', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def update_sync_settings( + self, + *, + request: Optional[Union[UpdateProfileSyncSettingsRequestBody, UpdateProfileSyncSettingsRequestBodyTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + """Update all sync settings""" # noqa: E501 + + if isinstance(request, dict): + request = UpdateProfileSyncSettingsRequestBody.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._update_profile_sync_settings_serialize( + update_profile_sync_settings_request=request, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='update-profile-syncSettings', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def update_sync_settings_async( + self, + *, + request: Optional[Union[UpdateProfileSyncSettingsRequestBody, UpdateProfileSyncSettingsRequestBodyTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.update_sync_settings( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _update_profile_sync_settings_serialize( + self, + update_profile_sync_settings_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if update_profile_sync_settings_request is not None: + _body_params = update_profile_sync_settings_request + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/profile/syncSettings', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + +# Speakeasy naming-drift compat alias (PascalCase preserves API/ID acronyms). +class CreateAPIKeyRequest(CreateApiKeyRequest): + pass +CreateAPIKeyRequestTypedDict = CreateApiKeyRequestTypedDict + + +# POC spelling of DeleteAPIKeyRequest, kept as an alias so existing imports keep working. +DeleteApiKeyRequest = DeleteAPIKeyRequest +DeleteApiKeyRequestTypedDict = DeleteAPIKeyRequestTypedDict diff --git a/platform/src/codat_platform/api/supplemental_data.py b/platform/src/codat_platform/api/supplemental_data.py new file mode 100644 index 000000000..b2aeecd6d --- /dev/null +++ b/platform/src/codat_platform/api/supplemental_data.py @@ -0,0 +1,498 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field, field_validator +from typing import Optional +from typing_extensions import Annotated +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connections import Connections +from codat_platform.models.shared.integrations import Integrations +from codat_platform.models.shared.supplementaldataconfiguration import SupplementalDataConfiguration + +from codat_platform.api_client import ApiClient, RequestSerialized +from codat_platform.api_response import ApiResponse +from codat_platform.exceptions import ApiException +from codat_platform.models.errors import ErrorMessage, SDKError +from codat_platform.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_platform.rest import RESTResponseType +from codat_platform.types import UNSET, OptionalNullable +from codat_platform.utils.retries import RetryConfig, execute_with_retries + + +class ConfigureSupplementalDataRequestTypedDict(TypedDict): + """TypedDict variant of ConfigureSupplementalDataRequest, for dict-literal request inputs.""" + platform_key: Annotated[str, Field(description="A unique 4-letter key to represent a platform in each integration.")] + data_type: Annotated[str, Field(description="Supported supplemental data data type.")] + supplemental_data_configuration: NotRequired[Annotated[Optional[SupplementalDataConfiguration], Field(description="The configuration for the specified platform and data type.")]] + + +class ConfigureSupplementalDataRequest(BaseModel): + """Request envelope for configure_supplemental_data.""" + platform_key: Annotated[str, Field(description="A unique 4-letter key to represent a platform in each integration.")] + data_type: Annotated[str, Field(description="Supported supplemental data data type.")] + supplemental_data_configuration: Annotated[Optional[SupplementalDataConfiguration], Field(description="The configuration for the specified platform and data type.")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetSupplementalDataConfigurationRequestTypedDict(TypedDict): + """TypedDict variant of GetSupplementalDataConfigurationRequest, for dict-literal request inputs.""" + platform_key: Annotated[str, Field(description="A unique 4-letter key to represent a platform in each integration.")] + data_type: Annotated[str, Field(description="Supported supplemental data data type.")] + + +class GetSupplementalDataConfigurationRequest(BaseModel): + """Request envelope for get_supplemental_data_configuration.""" + platform_key: Annotated[str, Field(description="A unique 4-letter key to represent a platform in each integration.")] + data_type: Annotated[str, Field(description="Supported supplemental data data type.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class SupplementalData: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def configure( + self, + *, + request: Union['ConfigureSupplementalDataRequest', 'ConfigureSupplementalDataRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + """Configure""" # noqa: E501 + + if isinstance(request, dict): + request = ConfigureSupplementalDataRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._configure_supplemental_data_serialize( + platform_key=request.platform_key, + data_type=request.data_type, + supplemental_data_configuration=request.supplemental_data_configuration, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='configure-supplemental-data', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def configure_async( + self, + *, + request: Union['ConfigureSupplementalDataRequest', 'ConfigureSupplementalDataRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.configure( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _configure_supplemental_data_serialize( + self, + platform_key, + data_type, + supplemental_data_configuration, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if platform_key is not None: + _path_params['platformKey'] = platform_key + if data_type is not None: + _path_params['dataType'] = data_type + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if supplemental_data_configuration is not None: + _body_params = supplemental_data_configuration + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/integrations/{platformKey}/dataTypes/{dataType}/supplementalDataConfig', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_configuration( + self, + *, + request: Union['GetSupplementalDataConfigurationRequest', 'GetSupplementalDataConfigurationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> SupplementalDataConfiguration: + """Get configuration""" # noqa: E501 + + if isinstance(request, dict): + request = GetSupplementalDataConfigurationRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_supplemental_data_configuration_serialize( + platform_key=request.platform_key, + data_type=request.data_type, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "SupplementalDataConfiguration", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-supplemental-data-configuration', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_configuration_async( + self, + *, + request: Union['GetSupplementalDataConfigurationRequest', 'GetSupplementalDataConfigurationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> SupplementalDataConfiguration: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_configuration( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_supplemental_data_configuration_serialize( + self, + platform_key, + data_type, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if platform_key is not None: + _path_params['platformKey'] = platform_key + if data_type is not None: + _path_params['dataType'] = data_type + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/integrations/{platformKey}/dataTypes/{dataType}/supplementalDataConfig', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/platform/src/codat_platform/api/webhooks.py b/platform/src/codat_platform/api/webhooks.py new file mode 100644 index 000000000..4ff620921 --- /dev/null +++ b/platform/src/codat_platform/api/webhooks.py @@ -0,0 +1,850 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field +from typing import Optional +from typing_extensions import Annotated +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connections import Connections +from codat_platform.models.shared.integrations import Integrations +from codat_platform.models.shared.webhookconsumer import WebhookConsumer +from codat_platform.models.shared.webhookconsumerprototype import WebhookConsumerPrototype, WebhookConsumerPrototypeTypedDict +from codat_platform.models.shared.webhookconsumers import WebhookConsumers +from codat_platform.models.webhook_zapier_key import WebhookZapierKey + +from codat_platform.api_client import ApiClient, RequestSerialized +from codat_platform.api_response import ApiResponse +from codat_platform.exceptions import ApiException +from codat_platform.models.errors import ErrorMessage, SDKError +from codat_platform.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_platform.rest import RESTResponseType +from codat_platform.types import UNSET, OptionalNullable +from codat_platform.utils.retries import RetryConfig, execute_with_retries + + +class CreateWebhookConsumerRequestTypedDict(TypedDict): + """TypedDict variant of CreateWebhookConsumerRequest, for dict-literal request inputs.""" + webhook_consumer_prototype: NotRequired[Optional[WebhookConsumerPrototype]] + + +class CreateWebhookConsumerRequest(BaseModel): + """Request envelope for create_webhook_consumer.""" + webhook_consumer_prototype: Optional[WebhookConsumerPrototype] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class DeleteWebhookConsumerRequestTypedDict(TypedDict): + """TypedDict variant of DeleteWebhookConsumerRequest, for dict-literal request inputs.""" + webhook_id: Annotated[str, Field(description="Unique identifier for the webhook consumer.")] + + +class DeleteWebhookConsumerRequest(BaseModel): + """Request envelope for delete_webhook_consumer.""" + webhook_id: Annotated[str, Field(description="Unique identifier for the webhook consumer.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class Webhooks: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def create_consumer( + self, + *, + request: Optional[Union[WebhookConsumerPrototype, WebhookConsumerPrototypeTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> WebhookConsumer: + """Create webhook consumer""" # noqa: E501 + + if isinstance(request, dict): + request = WebhookConsumerPrototype.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._create_webhook_consumer_serialize( + webhook_consumer_prototype=request, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "WebhookConsumer", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='create-webhook-consumer', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def create_consumer_async( + self, + *, + request: Optional[Union[WebhookConsumerPrototype, WebhookConsumerPrototypeTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> WebhookConsumer: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.create_consumer( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _create_webhook_consumer_serialize( + self, + webhook_consumer_prototype, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if webhook_consumer_prototype is not None: + _body_params = webhook_consumer_prototype + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/webhooks', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def delete_consumer( + self, + *, + request: Union['DeleteWebhookConsumerRequest', 'DeleteWebhookConsumerRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + """Delete webhook consumer""" # noqa: E501 + + if isinstance(request, dict): + request = DeleteWebhookConsumerRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._delete_webhook_consumer_serialize( + webhook_id=request.webhook_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='delete-webhook-consumer', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def delete_consumer_async( + self, + *, + request: Union['DeleteWebhookConsumerRequest', 'DeleteWebhookConsumerRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.delete_consumer( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _delete_webhook_consumer_serialize( + self, + webhook_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if webhook_id is not None: + _path_params['webhookId'] = webhook_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/webhooks/{webhookId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def list_consumers( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> WebhookConsumers: + """List webhook consumers""" # noqa: E501 + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._list_webhook_consumers_serialize( + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WebhookConsumers", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='list-webhook-consumers', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def list_consumers_async( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> WebhookConsumers: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list_consumers( + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _list_webhook_consumers_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/webhooks', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def rotate_zapier_key( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> WebhookZapierKey: + """Rotate Zapier key""" # noqa: E501 + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._rotate_zapier_key_serialize( + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "WebhookZapierKey", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='rotate-zapier-key', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def rotate_zapier_key_async( + self, + *, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> WebhookZapierKey: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.rotate_zapier_key( + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _rotate_zapier_key_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/webhooks/integrationKeys/zapier', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/platform/src/codat_platform/api_client.py b/platform/src/codat_platform/api_client.py new file mode 100644 index 000000000..90fd46239 --- /dev/null +++ b/platform/src/codat_platform/api_client.py @@ -0,0 +1,803 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import datetime +from dateutil.parser import parse +from enum import Enum +import decimal +import json +import mimetypes +import os +import re +import tempfile + +from urllib.parse import quote +from typing import Tuple, Optional, List, Dict, Union +from pydantic import SecretStr + +from codat_platform.configuration import Configuration +from codat_platform.api_response import ApiResponse, T as ApiResponseT +import codat_platform.models +from codat_platform import rest +from codat_platform.exceptions import ( + ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException +) + +RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]] + +class ApiClient: + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + """ + + PRIMITIVE_TYPES = (float, bool, bytes, str, int) + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int, # TODO remove as only py3 is supported? + 'float': float, + 'str': str, + 'bool': bool, + 'date': datetime.date, + 'datetime': datetime.datetime, + 'decimal': decimal.Decimal, + 'object': object, + } + _pool = None + + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None + ) -> None: + # use default configuration if none is provided + if configuration is None: + configuration = Configuration.get_default() + self.configuration = configuration + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + self.client_side_validation = configuration.client_side_validation + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + pass + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] + + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + + _default = None + + @classmethod + def get_default(cls): + """Return new instance of ApiClient. + + This method returns newly created, based on default constructor, + object of ApiClient class or returns a copy of default + ApiClient. + + :return: The ApiClient object. + """ + if cls._default is None: + cls._default = ApiClient() + return cls._default + + @classmethod + def set_default(cls, default): + """Set default instance of ApiClient. + + It stores default ApiClient. + + :param default: object of ApiClient. + """ + cls._default = default + + def param_serialize( + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None + ) -> RequestSerialized: + + """Builds the HTTP request params needed by the request. + :param method: Method to call. + :param resource_path: Path to method endpoint. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :return: tuple of form (path, http_method, query_params, header_params, + body, post_params, files) + """ + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict( + self.parameters_to_tuples(header_params,collection_formats) + ) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples( + path_params, + collection_formats + ) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) + if files: + post_params.extend(self.files_parameters(files)) + + # auth setting + self.update_params_for_auth( + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # request url + if _host is None or self.configuration.ignore_operation_servers: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) + url += "?" + url_query + + return method, url, header_params, body, post_params + + + def call_api( + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None, + operation_id=None, + ) -> rest.RESTResponse: + """Makes the HTTP request (synchronous) + :param method: Method to call. + :param url: Path to method endpoint. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param _request_timeout: timeout setting for this request. + :return: RESTResponse + """ + + try: + # perform request and return response + response_data = self.rest_client.request( + method, url, + headers=header_params, + body=body, post_params=post_params, + _request_timeout=_request_timeout + ) + + except ApiException as e: + raise e + + return response_data + + def response_deserialize( + self, + response_data: rest.RESTResponse, + response_types_map: Optional[Dict[str, ApiResponseT]]=None + ) -> ApiResponse[ApiResponseT]: + """Deserializes response into an object. + :param response_data: RESTResponse object to be deserialized. + :param response_types_map: dict of response types. + :return: ApiResponse + """ + + msg = "RESTResponse.read() must be called before passing it to response_deserialize()" + assert response_data.data is not None, msg + + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + + # deserialize response data + response_text = None + return_data = None + try: + if response_type == "bytearray": + return_data = response_data.data + elif response_type == "file": + return_data = self.__deserialize_file(response_data) + elif response_type is not None: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_text = response_data.data.decode(encoding) + return_data = self.deserialize(response_text, response_type, content_type) + finally: + if not 200 <= response_data.status <= 299: + raise ApiException.from_response( + http_resp=response_data, + body=response_text, + data=return_data, + ) + + return ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data + ) + + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. + + If obj is None, return None. + If obj is SecretStr, return obj.get_secret_value() + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is decimal.Decimal return string representation. + If obj is list, sanitize each element in the list. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. + + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if obj is None: + return None + elif isinstance(obj, Enum): + return obj.value + elif isinstance(obj, SecretStr): + return obj.get_secret_value() + elif isinstance(obj, self.PRIMITIVE_TYPES): + return obj + elif isinstance(obj, list): + return [ + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ] + elif isinstance(obj, tuple): + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) + elif isinstance(obj, (datetime.datetime, datetime.date)): + return obj.isoformat() + elif isinstance(obj, decimal.Decimal): + return str(obj) + + elif isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `openapi_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')): + obj_dict = obj.to_dict() + else: + obj_dict = obj.__dict__ + + return { + key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items() + } + + def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialized object, or string of class name. + :param content_type: content type of response. + + :return: deserialized object. + """ + + # fetch data from response object + if content_type is None: + try: + data = json.loads(response_text) + except ValueError: + data = response_text + elif re.match(r'^application/(json|[\w!#$&.+-^_]+\+json)\s*(;|$)', content_type, re.IGNORECASE): + if response_text == "": + data = "" + else: + data = json.loads(response_text) + elif re.match(r'^text\/[a-z.+-]+\s*(;|$)', content_type, re.IGNORECASE): + data = response_text + else: + raise ApiException( + status=0, + reason="Unsupported content type: {0}".format(content_type) + ) + + return self.__deserialize(data, response_type) + + def __deserialize(self, data, klass): + """Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if isinstance(klass, str): + if klass.startswith('List['): + m = re.match(r'List\[(.*)]', klass) + assert m is not None, "Malformed List type definition" + sub_kls = m.group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] + + if klass.startswith('Dict['): + m = re.match(r'Dict\[([^,]*), (.*)]', klass) + assert m is not None, "Malformed Dict type definition" + sub_kls = m.group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in data.items()} + + # convert str to class + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] + else: + klass = getattr(codat_platform.models, klass) + + if klass in self.PRIMITIVE_TYPES: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object(data) + elif klass == datetime.date: + return self.__deserialize_date(data) + elif klass == datetime.datetime: + return self.__deserialize_datetime(data) + elif klass == decimal.Decimal: + return decimal.Decimal(data) + elif issubclass(klass, Enum): + return self.__deserialize_enum(data, klass) + else: + return self.__deserialize_model(data, klass) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params: List[Tuple[str, str]] = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + + def parameters_to_url_query(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: URL query string (e.g. a=Hello%20World&b=123) + """ + new_params: List[Tuple[str, str]] = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if isinstance(v, bool): + v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) + if isinstance(v, dict): + v = json.dumps(v) + + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, str(value)) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(quote(str(value)) for value in v)) + ) + else: + new_params.append((k, quote(str(v)))) + + return "&".join(["=".join(map(str, item)) for item in new_params]) + + def files_parameters( + self, + files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]], + ): + """Builds form parameters. + + :param files: File parameters. + :return: Form parameters with files. + """ + params = [] + for k, v in files.items(): + mimetype = None + if isinstance(v, str): + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + elif isinstance(v, bytes): + filename = k + filedata = v + elif isinstance(v, tuple): + if len(v) == 3: + filename, filedata, mimetype = v + else: + filename, filedata = v + elif isinstance(v, list): + for file_param in v: + params.extend(self.files_parameters({k: file_param})) + continue + else: + raise ValueError("Unsupported file value") + mimetype = mimetype or ( + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) + params.append( + tuple([k, tuple([filename, filedata, mimetype])]) + ) + return params + + def select_header_accept(self, accepts: List[str]) -> Optional[str]: + """Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return None + + for accept in accepts: + if re.search('json', accept, re.IGNORECASE): + return accept + + return accepts[0] + + def select_header_content_type(self, content_types): + """Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return None + + for content_type in content_types: + if re.search('json', content_type, re.IGNORECASE): + return content_type + + return content_types[0] + + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None + ) -> None: + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param request_auth: if set, the provided settings will + override the token in the configuration. + """ + if not auth_settings: + return + + if request_auth: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) + else: + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + auth_setting + ) + + def _apply_auth_params( + self, + headers, + queries, + resource_path, + method, + body, + auth_setting + ) -> None: + """Updates the request parameters based on a single auth_setting + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param auth_setting: auth settings for the endpoint + """ + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + queries.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + + def __deserialize_file(self, response): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + handle file downloading + save response body into a tmp file and return the instance + + :param response: RESTResponse. + :return: file path. + """ + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + m = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition + ) + assert m is not None, "Unexpected 'content-disposition' header value" + filename = m.group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. + + :param data: str. + :param klass: class literal. + + :return: int, long, float, str, bool. + """ + try: + return klass(data) + except UnicodeEncodeError: + return str(data) + except TypeError: + return data + + def __deserialize_object(self, value): + """Return an original value. + + :return: object. + """ + return value + + def __deserialize_date(self, string): + """Deserializes string to date. + + :param string: str. + :return: date. + """ + try: + return parse(string).date() + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason="Failed to parse `{0}` as date object".format(string) + ) + + def __deserialize_datetime(self, string): + """Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ + try: + return parse(string) + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as datetime object" + .format(string) + ) + ) + + def __deserialize_enum(self, data, klass): + """Deserializes primitive type to enum. + + :param data: primitive type. + :param klass: class literal. + :return: enum value. + """ + try: + return klass(data) + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as `{1}`" + .format(data, klass) + ) + ) + + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + + return klass.from_dict(data) diff --git a/platform/src/codat_platform/api_response.py b/platform/src/codat_platform/api_response.py new file mode 100644 index 000000000..8a1236a62 --- /dev/null +++ b/platform/src/codat_platform/api_response.py @@ -0,0 +1,21 @@ +"""API response object.""" + +from __future__ import annotations +from typing import Optional, Generic, Mapping, TypeVar +from pydantic import Field, BaseModel + +T = TypeVar("T") + +class ApiResponse(BaseModel, Generic[T]): + """ + API response object + """ + + status_code: int = Field(description="HTTP status code") + headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: bytes = Field(description="Raw data (HTTP response body)") + + model_config = { + "arbitrary_types_allowed": True + } diff --git a/platform/src/codat_platform/basesdk.py b/platform/src/codat_platform/basesdk.py deleted file mode 100644 index e13deffd2..000000000 --- a/platform/src/codat_platform/basesdk.py +++ /dev/null @@ -1,393 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from .sdkconfiguration import SDKConfiguration -from codat_platform import utils -from codat_platform._hooks import ( - AfterErrorContext, - AfterSuccessContext, - BeforeRequestContext, - HookContext, -) -from codat_platform.models import errors -from codat_platform.utils import ( - RetryConfig, - SerializedRequestBody, - get_body_content, - run_sync_in_thread, -) -import httpx -from typing import Callable, List, Mapping, Optional, Tuple -from urllib.parse import parse_qs, urlparse - - -class BaseSDK: - sdk_configuration: SDKConfiguration - parent_ref: Optional[object] = None - """ - Reference to the root SDK instance, if any. This will prevent it from - being garbage collected while there are active streams. - """ - - def __init__( - self, - sdk_config: SDKConfiguration, - parent_ref: Optional[object] = None, - ) -> None: - self.sdk_configuration = sdk_config - self.parent_ref = parent_ref - - def _get_url(self, base_url, url_variables): - sdk_url, sdk_variables = self.sdk_configuration.get_server_details() - - if base_url is None: - base_url = sdk_url - - if url_variables is None: - url_variables = sdk_variables - - return utils.template_url(base_url, url_variables) - - def _build_request_async( - self, - method, - path, - base_url, - url_variables, - request, - request_body_required, - request_has_path_params, - request_has_query_params, - user_agent_header, - accept_header_value, - _globals=None, - security=None, - timeout_ms: Optional[int] = None, - get_serialized_body: Optional[ - Callable[[], Optional[SerializedRequestBody]] - ] = None, - url_override: Optional[str] = None, - http_headers: Optional[Mapping[str, str]] = None, - allow_empty_value: Optional[List[str]] = None, - allowed_fields: Optional[List[str]] = None, - ) -> httpx.Request: - client = self.sdk_configuration.async_client - return self._build_request_with_client( - client, - method, - path, - base_url, - url_variables, - request, - request_body_required, - request_has_path_params, - request_has_query_params, - user_agent_header, - accept_header_value, - _globals, - security, - timeout_ms, - get_serialized_body, - url_override, - http_headers, - allow_empty_value, - allowed_fields, - ) - - def _build_request( - self, - method, - path, - base_url, - url_variables, - request, - request_body_required, - request_has_path_params, - request_has_query_params, - user_agent_header, - accept_header_value, - _globals=None, - security=None, - timeout_ms: Optional[int] = None, - get_serialized_body: Optional[ - Callable[[], Optional[SerializedRequestBody]] - ] = None, - url_override: Optional[str] = None, - http_headers: Optional[Mapping[str, str]] = None, - allow_empty_value: Optional[List[str]] = None, - allowed_fields: Optional[List[str]] = None, - ) -> httpx.Request: - client = self.sdk_configuration.client - return self._build_request_with_client( - client, - method, - path, - base_url, - url_variables, - request, - request_body_required, - request_has_path_params, - request_has_query_params, - user_agent_header, - accept_header_value, - _globals, - security, - timeout_ms, - get_serialized_body, - url_override, - http_headers, - allow_empty_value, - allowed_fields, - ) - - def _build_request_with_client( - self, - client, - method, - path, - base_url, - url_variables, - request, - request_body_required, - request_has_path_params, - request_has_query_params, - user_agent_header, - accept_header_value, - _globals=None, - security=None, - timeout_ms: Optional[int] = None, - get_serialized_body: Optional[ - Callable[[], Optional[SerializedRequestBody]] - ] = None, - url_override: Optional[str] = None, - http_headers: Optional[Mapping[str, str]] = None, - allow_empty_value: Optional[List[str]] = None, - allowed_fields: Optional[List[str]] = None, - ) -> httpx.Request: - query_params = {} - - url = url_override - if url is None: - url = utils.generate_url( - self._get_url(base_url, url_variables), - path, - request if request_has_path_params else None, - _globals if request_has_path_params else None, - ) - - query_params = utils.get_query_params( - request if request_has_query_params else None, - _globals if request_has_query_params else None, - allow_empty_value, - ) - else: - # Pick up the query parameter from the override so they can be - # preserved when building the request later on (necessary as of - # httpx 0.28). - parsed_override = urlparse(str(url_override)) - query_params = parse_qs(parsed_override.query, keep_blank_values=True) - - headers = utils.get_headers(request, _globals) - headers["Accept"] = accept_header_value - headers[user_agent_header] = self.sdk_configuration.user_agent - - if security is not None: - if callable(security): - security = security() - - if security is not None: - security_headers, security_query_params = utils.get_security( - security, allowed_fields - ) - headers = {**headers, **security_headers} - query_params = {**query_params, **security_query_params} - - serialized_request_body = SerializedRequestBody() - if get_serialized_body is not None: - rb = get_serialized_body() - if request_body_required and rb is None: - raise ValueError("request body is required") - - if rb is not None: - serialized_request_body = rb - - if ( - serialized_request_body.media_type is not None - and serialized_request_body.media_type - not in ( - "multipart/form-data", - "multipart/mixed", - ) - ): - headers["content-type"] = serialized_request_body.media_type - - if http_headers is not None: - for header, value in http_headers.items(): - headers[header] = value - - timeout = timeout_ms / 1000 if timeout_ms is not None else None - - return client.build_request( - method, - url, - params=query_params, - content=serialized_request_body.content, - data=serialized_request_body.data, - files=serialized_request_body.files, - headers=headers, - timeout=timeout if timeout is not None else httpx.USE_CLIENT_DEFAULT, - ) - - def do_request( - self, - hook_ctx: HookContext, - request: httpx.Request, - is_error_status_code: Callable[[int], bool], - stream: bool = False, - retry_config: Optional[Tuple[RetryConfig, List[str]]] = None, - ) -> httpx.Response: - client = self.sdk_configuration.client - logger = self.sdk_configuration.debug_logger - - hooks = self.sdk_configuration.__dict__["_hooks"] - - def do(): - http_res = None - try: - req = hooks.before_request(BeforeRequestContext(hook_ctx), request) - if "timeout" in request.extensions and "timeout" not in req.extensions: - req.extensions["timeout"] = request.extensions["timeout"] - logger.debug( - "Request:\nMethod: %s\nURL: %s\nHeaders: %s\nBody: %s", - req.method, - req.url, - req.headers, - get_body_content(req), - ) - - if client is None: - raise ValueError("client is required") - - http_res = client.send(req, stream=stream) - except Exception as e: - _, e = hooks.after_error(AfterErrorContext(hook_ctx), None, e) - if e is not None: - logger.debug("Request Exception", exc_info=True) - raise e - - if http_res is None: - logger.debug("Raising no response SDK error") - raise errors.NoResponseError("No response received") - - logger.debug( - "Response:\nStatus Code: %s\nURL: %s\nHeaders: %s\nBody: %s", - http_res.status_code, - http_res.url, - http_res.headers, - "" if stream else http_res.text, - ) - - return http_res - - if retry_config is not None: - http_res = utils.retry(do, utils.Retries(retry_config[0], retry_config[1])) - else: - http_res = do() - - if is_error_status_code(http_res.status_code): - result, err = hooks.after_error(AfterErrorContext(hook_ctx), http_res, None) - if err is not None: - logger.debug("Request Exception", exc_info=True) - raise err - if result is not None: - http_res = result - else: - logger.debug("Raising unexpected SDK error") - raise errors.SDKError("Unexpected error occurred", http_res) - else: - http_res = hooks.after_success(AfterSuccessContext(hook_ctx), http_res) - - return http_res - - async def do_request_async( - self, - hook_ctx: HookContext, - request: httpx.Request, - is_error_status_code: Callable[[int], bool], - stream: bool = False, - retry_config: Optional[Tuple[RetryConfig, List[str]]] = None, - ) -> httpx.Response: - client = self.sdk_configuration.async_client - logger = self.sdk_configuration.debug_logger - - hooks = self.sdk_configuration.__dict__["_hooks"] - - async def do(): - http_res = None - try: - req = await run_sync_in_thread( - hooks.before_request, BeforeRequestContext(hook_ctx), request - ) - - if "timeout" in request.extensions and "timeout" not in req.extensions: - req.extensions["timeout"] = request.extensions["timeout"] - logger.debug( - "Request:\nMethod: %s\nURL: %s\nHeaders: %s\nBody: %s", - req.method, - req.url, - req.headers, - get_body_content(req), - ) - - if client is None: - raise ValueError("client is required") - - http_res = await client.send(req, stream=stream) - except Exception as e: - _, e = await run_sync_in_thread( - hooks.after_error, AfterErrorContext(hook_ctx), None, e - ) - - if e is not None: - logger.debug("Request Exception", exc_info=True) - raise e - - if http_res is None: - logger.debug("Raising no response SDK error") - raise errors.NoResponseError("No response received") - - logger.debug( - "Response:\nStatus Code: %s\nURL: %s\nHeaders: %s\nBody: %s", - http_res.status_code, - http_res.url, - http_res.headers, - "" if stream else http_res.text, - ) - - return http_res - - if retry_config is not None: - http_res = await utils.retry_async( - do, utils.Retries(retry_config[0], retry_config[1]) - ) - else: - http_res = await do() - - if is_error_status_code(http_res.status_code): - result, err = await run_sync_in_thread( - hooks.after_error, AfterErrorContext(hook_ctx), http_res, None - ) - - if err is not None: - logger.debug("Request Exception", exc_info=True) - raise err - if result is not None: - http_res = result - else: - logger.debug("Raising unexpected SDK error") - raise errors.SDKError("Unexpected error occurred", http_res) - else: - http_res = await run_sync_in_thread( - hooks.after_success, AfterSuccessContext(hook_ctx), http_res - ) - - return http_res diff --git a/platform/src/codat_platform/companies.py b/platform/src/codat_platform/companies.py index c302d956b..0e641bfcf 100644 --- a/platform/src/codat_platform/companies.py +++ b/platform/src/codat_platform/companies.py @@ -1,2511 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.companies — re-export of the companies method group.""" -from .basesdk import BaseSDK -from codat_platform import utils -from codat_platform._hooks import HookContext -from codat_platform.models import errors, operations, shared -from codat_platform.types import BaseModel, OptionalNullable, UNSET -from codat_platform.utils.unmarshal_json_response import unmarshal_json_response -from typing import Any, Mapping, Optional, Union, cast - - -class Companies(BaseSDK): - r"""Create and manage your SMB users' companies.""" - - def add_product( - self, - *, - request: Union[ - operations.AddProductRequest, operations.AddProductRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Add product - - Use the *Add product* endpoint to enable a product for the company specified by `companyId`. - - > Note: This feature is currently in alpha and available only to participants in the development program. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.AddProductRequest) - request = cast(operations.AddProductRequest, request) - - req = self._build_request( - method="PUT", - path="/companies/{companyId}/products/{productIdentifier}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="add-product", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def add_product_async( - self, - *, - request: Union[ - operations.AddProductRequest, operations.AddProductRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Add product - - Use the *Add product* endpoint to enable a product for the company specified by `companyId`. - - > Note: This feature is currently in alpha and available only to participants in the development program. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.AddProductRequest) - request = cast(operations.AddProductRequest, request) - - req = self._build_request_async( - method="PUT", - path="/companies/{companyId}/products/{productIdentifier}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="add-product", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def create( - self, - *, - request: Optional[ - Union[shared.CompanyRequestBody, shared.CompanyRequestBodyTypedDict] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Create company - - Use the *Create company* endpoint to create a new [company](https://docs.codat.io/platform-api#/schemas/Company) that represents your customer in Codat. - - A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - If forbidden characters (see `name` pattern) are present in the request, a company will be created with the forbidden characters removed. For example, `Company (Codat[1])` with be created as `Company Codat1`. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, Optional[shared.CompanyRequestBody]) - request = cast(Optional[shared.CompanyRequestBody], request) - - req = self._build_request( - method="POST", - path="/companies", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, False, True, "json", Optional[shared.CompanyRequestBody] - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def create_async( - self, - *, - request: Optional[ - Union[shared.CompanyRequestBody, shared.CompanyRequestBodyTypedDict] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Create company - - Use the *Create company* endpoint to create a new [company](https://docs.codat.io/platform-api#/schemas/Company) that represents your customer in Codat. - - A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - If forbidden characters (see `name` pattern) are present in the request, a company will be created with the forbidden characters removed. For example, `Company (Codat[1])` with be created as `Company Codat1`. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, Optional[shared.CompanyRequestBody]) - request = cast(Optional[shared.CompanyRequestBody], request) - - req = self._build_request_async( - method="POST", - path="/companies", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, False, True, "json", Optional[shared.CompanyRequestBody] - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def delete( - self, - *, - request: Union[ - operations.DeleteCompanyRequest, operations.DeleteCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Delete a company - - The *Delete company* endpoint permanently deletes a [company](https://docs.codat.io/platform-api#/schemas/Company), its [connections](https://docs.codat.io/platform-api#/schemas/Connection) and any cached data. This operation is irreversible. - - A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DeleteCompanyRequest) - request = cast(operations.DeleteCompanyRequest, request) - - req = self._build_request( - method="DELETE", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="delete-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def delete_async( - self, - *, - request: Union[ - operations.DeleteCompanyRequest, operations.DeleteCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Delete a company - - The *Delete company* endpoint permanently deletes a [company](https://docs.codat.io/platform-api#/schemas/Company), its [connections](https://docs.codat.io/platform-api#/schemas/Connection) and any cached data. This operation is irreversible. - - A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DeleteCompanyRequest) - request = cast(operations.DeleteCompanyRequest, request) - - req = self._build_request_async( - method="DELETE", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="delete-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get( - self, - *, - request: Union[ - operations.GetCompanyRequest, operations.GetCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Get company - - The *Get company* endpoint returns a single company for a given `companyId`. - - A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanyRequest) - request = cast(operations.GetCompanyRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_async( - self, - *, - request: Union[ - operations.GetCompanyRequest, operations.GetCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Get company - - The *Get company* endpoint returns a single company for a given `companyId`. - - A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanyRequest) - request = cast(operations.GetCompanyRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get_access_token( - self, - *, - request: Union[ - operations.GetCompanyAccessTokenRequest, - operations.GetCompanyAccessTokenRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanyAccessToken: - r"""Get company access token - - Use the _Get company access token_ endpoint to return an access token for the specified company ID. The token is valid for one day. - - The token is required by Codat's embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to verify the identity of the user and improve the reliability of data provided by them. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanyAccessTokenRequest) - request = cast(operations.GetCompanyAccessTokenRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/accessToken", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company-access-token", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.CompanyAccessToken, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_access_token_async( - self, - *, - request: Union[ - operations.GetCompanyAccessTokenRequest, - operations.GetCompanyAccessTokenRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanyAccessToken: - r"""Get company access token - - Use the _Get company access token_ endpoint to return an access token for the specified company ID. The token is valid for one day. - - The token is required by Codat's embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to verify the identity of the user and improve the reliability of data provided by them. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanyAccessTokenRequest) - request = cast(operations.GetCompanyAccessTokenRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/accessToken", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company-access-token", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.CompanyAccessToken, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get_company_sync_settings( - self, - *, - request: Union[ - operations.GetCompanySyncSettingsRequest, - operations.GetCompanySyncSettingsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanySyncSettings: - r"""Get company sync settings - - Retrieve the [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings) for a specific company. This includes how often data types should be queued to be updated, and how much history should be fetched. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanySyncSettingsRequest) - request = cast(operations.GetCompanySyncSettingsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/syncSettings", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company-syncSettings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.CompanySyncSettings, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_company_sync_settings_async( - self, - *, - request: Union[ - operations.GetCompanySyncSettingsRequest, - operations.GetCompanySyncSettingsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanySyncSettings: - r"""Get company sync settings - - Retrieve the [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings) for a specific company. This includes how often data types should be queued to be updated, and how much history should be fetched. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanySyncSettingsRequest) - request = cast(operations.GetCompanySyncSettingsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/syncSettings", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company-syncSettings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.CompanySyncSettings, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def list( - self, - *, - request: Union[ - operations.ListCompaniesRequest, operations.ListCompaniesRequestTypedDict - ] = operations.ListCompaniesRequest(), - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Companies: - r"""List companies - - The *List companies* endpoint returns a list of [companies](https://docs.codat.io/platform-api#/schemas/Company) associated to your instances. - - A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - ## Filter by tags - - The *List companies* endpoint supports the filtering of companies using [tags](https://docs.codat.io/using-the-api/managing-companies#add-metadata-to-a-company). It supports the following operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying): - - - equals (`=`) - - not equals (`!=`) - - contains (`~`) - - For example, you can use the querying to filter companies tagged with a specific foreign key, region, or owning team: - - Foreign key: `uid = {yourCustomerId}` - - Region: `region != uk` - - Owning team and region: `region = uk && owningTeam = invoice-finance` - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListCompaniesRequest) - request = cast(operations.ListCompaniesRequest, request) - - req = self._build_request( - method="GET", - path="/companies", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-companies", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Companies, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def list_async( - self, - *, - request: Union[ - operations.ListCompaniesRequest, operations.ListCompaniesRequestTypedDict - ] = operations.ListCompaniesRequest(), - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Companies: - r"""List companies - - The *List companies* endpoint returns a list of [companies](https://docs.codat.io/platform-api#/schemas/Company) associated to your instances. - - A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - ## Filter by tags - - The *List companies* endpoint supports the filtering of companies using [tags](https://docs.codat.io/using-the-api/managing-companies#add-metadata-to-a-company). It supports the following operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying): - - - equals (`=`) - - not equals (`!=`) - - contains (`~`) - - For example, you can use the querying to filter companies tagged with a specific foreign key, region, or owning team: - - Foreign key: `uid = {yourCustomerId}` - - Region: `region != uk` - - Owning team and region: `region = uk && owningTeam = invoice-finance` - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListCompaniesRequest) - request = cast(operations.ListCompaniesRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-companies", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Companies, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def refresh_product_data( - self, - *, - request: Union[ - operations.RefreshProductDataRequest, - operations.RefreshProductDataRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Refresh product data - - Use the **Refresh product data** endpoint to manually refresh data for a custom product for a specific company. - - ### Tips and traps - - - This endpoint only supports refreshing data for **custom products** and can't be used for Codat's standard solutions. Refer to [individual solutions' documentation](https://docs.codat.io/) instead. - - If a data sync is already in progress for a custom product, the refresh request will return a `Bad request (400)` response. - - If a company has multiple custom products enabled, you can refresh data for each product individually. - - Optionally include a request body with `dataTypes` to refresh only selected data types for the specified product. If omitted, the product's scheduled refresh is triggered as usual. - - When specifying `dataTypes`, each value must be a valid data type supported by the product. Invalid values will result in a `Bad request (400)` response listing valid options. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.RefreshProductDataRequest) - request = cast(operations.RefreshProductDataRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/products/{productIdentifier}/refresh", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.request_body if request is not None else None, - False, - True, - "json", - Optional[operations.RefreshProductDataRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="refresh-product-data", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "202", "*"): - return - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def refresh_product_data_async( - self, - *, - request: Union[ - operations.RefreshProductDataRequest, - operations.RefreshProductDataRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Refresh product data - - Use the **Refresh product data** endpoint to manually refresh data for a custom product for a specific company. - - ### Tips and traps - - - This endpoint only supports refreshing data for **custom products** and can't be used for Codat's standard solutions. Refer to [individual solutions' documentation](https://docs.codat.io/) instead. - - If a data sync is already in progress for a custom product, the refresh request will return a `Bad request (400)` response. - - If a company has multiple custom products enabled, you can refresh data for each product individually. - - Optionally include a request body with `dataTypes` to refresh only selected data types for the specified product. If omitted, the product's scheduled refresh is triggered as usual. - - When specifying `dataTypes`, each value must be a valid data type supported by the product. Invalid values will result in a `Bad request (400)` response listing valid options. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.RefreshProductDataRequest) - request = cast(operations.RefreshProductDataRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/products/{productIdentifier}/refresh", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.request_body if request is not None else None, - False, - True, - "json", - Optional[operations.RefreshProductDataRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="refresh-product-data", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "202", "*"): - return - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def remove_product( - self, - *, - request: Union[ - operations.RemoveProductRequest, operations.RemoveProductRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Remove product - - Use the *Remove product* endpoint to disable a product for the company specified by `companyId`. - - > Note: This feature is currently in alpha and available only to participants in the development program. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.RemoveProductRequest) - request = cast(operations.RemoveProductRequest, request) - - req = self._build_request( - method="DELETE", - path="/companies/{companyId}/products/{productIdentifier}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="remove-product", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def remove_product_async( - self, - *, - request: Union[ - operations.RemoveProductRequest, operations.RemoveProductRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Remove product - - Use the *Remove product* endpoint to disable a product for the company specified by `companyId`. - - > Note: This feature is currently in alpha and available only to participants in the development program. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.RemoveProductRequest) - request = cast(operations.RemoveProductRequest, request) - - req = self._build_request_async( - method="DELETE", - path="/companies/{companyId}/products/{productIdentifier}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="remove-product", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def replace( - self, - *, - request: Union[ - operations.ReplaceCompanyRequest, operations.ReplaceCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Replace company - - Use the *Replace company* endpoint to replace the existing name, description, and tags of the company. Calling the endpoint will replace existing values even if new values haven't been defined in the payload. - - A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ReplaceCompanyRequest) - request = cast(operations.ReplaceCompanyRequest, request) - - req = self._build_request( - method="PUT", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.company_request_body if request is not None else None, - False, - True, - "json", - Optional[shared.CompanyRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="replace-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def replace_async( - self, - *, - request: Union[ - operations.ReplaceCompanyRequest, operations.ReplaceCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Replace company - - Use the *Replace company* endpoint to replace the existing name, description, and tags of the company. Calling the endpoint will replace existing values even if new values haven't been defined in the payload. - - A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ReplaceCompanyRequest) - request = cast(operations.ReplaceCompanyRequest, request) - - req = self._build_request_async( - method="PUT", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.company_request_body if request is not None else None, - False, - True, - "json", - Optional[shared.CompanyRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="replace-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def set_company_sync_settings( - self, - *, - request: Union[ - operations.SetCompanySyncSettingsRequest, - operations.SetCompanySyncSettingsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Set company sync settings - - Set the sync settings for a specific company. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.SetCompanySyncSettingsRequest) - request = cast(operations.SetCompanySyncSettingsRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/syncSettings", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.request_body if request is not None else None, - False, - True, - "json", - Optional[operations.SetCompanySyncSettingsRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="set-company-syncSettings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def set_company_sync_settings_async( - self, - *, - request: Union[ - operations.SetCompanySyncSettingsRequest, - operations.SetCompanySyncSettingsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Set company sync settings - - Set the sync settings for a specific company. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.SetCompanySyncSettingsRequest) - request = cast(operations.SetCompanySyncSettingsRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/syncSettings", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.request_body if request is not None else None, - False, - True, - "json", - Optional[operations.SetCompanySyncSettingsRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="set-company-syncSettings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def update( - self, - *, - request: Union[ - operations.UpdateCompanyRequest, operations.UpdateCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Update company - - Use the *Update company* endpoint to update the name, description, or tags of the company. - - The *Update company* endpoint doesn't have any required fields. If any of the fields provided are `null` or not provided, they won't be included in the update. - - A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UpdateCompanyRequest) - request = cast(operations.UpdateCompanyRequest, request) - - req = self._build_request( - method="PATCH", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.company_update_request if request is not None else None, - False, - True, - "json", - Optional[shared.CompanyUpdateRequest], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def update_async( - self, - *, - request: Union[ - operations.UpdateCompanyRequest, operations.UpdateCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Update company - - Use the *Update company* endpoint to update the name, description, or tags of the company. - - The *Update company* endpoint doesn't have any required fields. If any of the fields provided are `null` or not provided, they won't be included in the update. - - A [company](https://docs.codat.io/platform-api#/schemas/Company) represents a business sharing access to their data. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UpdateCompanyRequest) - request = cast(operations.UpdateCompanyRequest, request) - - req = self._build_request_async( - method="PATCH", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.company_update_request if request is not None else None, - False, - True, - "json", - Optional[shared.CompanyUpdateRequest], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_platform.api.companies import Companies diff --git a/platform/src/codat_platform/configuration.py b/platform/src/codat_platform/configuration.py new file mode 100644 index 000000000..6255a6255 --- /dev/null +++ b/platform/src/codat_platform/configuration.py @@ -0,0 +1,596 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import copy +import http.client as httplib +import logging +from logging import FileHandler +import multiprocessing +import sys +from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict +from typing_extensions import NotRequired, Self + +import urllib3 + + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' +} + +ServerVariablesT = Dict[str, str] + +GenericAuthSetting = TypedDict( + "GenericAuthSetting", + { + "type": str, + "in": str, + "key": str, + "value": str, + }, +) + + +OAuth2AuthSetting = TypedDict( + "OAuth2AuthSetting", + { + "type": Literal["oauth2"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +APIKeyAuthSetting = TypedDict( + "APIKeyAuthSetting", + { + "type": Literal["api_key"], + "in": str, + "key": str, + "value": Optional[str], + }, +) + + +BasicAuthSetting = TypedDict( + "BasicAuthSetting", + { + "type": Literal["basic"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": Optional[str], + }, +) + + +BearerFormatAuthSetting = TypedDict( + "BearerFormatAuthSetting", + { + "type": Literal["bearer"], + "in": Literal["header"], + "format": Literal["JWT"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +BearerAuthSetting = TypedDict( + "BearerAuthSetting", + { + "type": Literal["bearer"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +HTTPSignatureAuthSetting = TypedDict( + "HTTPSignatureAuthSetting", + { + "type": Literal["http-signature"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": None, + }, +) + + +AuthSettings = TypedDict( + "AuthSettings", + { + "auth_header": APIKeyAuthSetting, + }, + total=False, +) + + +class HostSettingVariable(TypedDict): + description: str + default_value: str + enum_values: List[str] + + +class HostSetting(TypedDict): + url: str + description: str + variables: NotRequired[Dict[str, HostSettingVariable]] + + +class Configuration: + """This class contains various settings of the API client. + + :param host: Base url. + :param ignore_operation_servers + Boolean to ignore operation servers for the API client. + Config will use `host` as the base url regardless of the operation servers. + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer). + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication. + :param password: Password for HTTP basic authentication. + :param access_token: Access token. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum + values before. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format. + :param retries: Number of retries for API requests. + + :Example: + + API Key Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + cookieAuth: # name for the security scheme + type: apiKey + in: cookie + name: JSESSIONID # cookie name + + You can programmatically set the cookie: + +conf = codat_platform.Configuration( + api_key={'cookieAuth': 'abc123'} + api_key_prefix={'cookieAuth': 'JSESSIONID'} +) + + The following cookie will be added to the HTTP request: + Cookie: JSESSIONID abc123 + """ + + _default: ClassVar[Optional[Self]] = None + + def __init__( + self, + host: Optional[str]=None, + api_key: Optional[Dict[str, str]]=None, + api_key_prefix: Optional[Dict[str, str]]=None, + username: Optional[str]=None, + password: Optional[str]=None, + access_token: Optional[str]=None, + server_index: Optional[int]=None, + server_variables: Optional[ServerVariablesT]=None, + server_operation_index: Optional[Dict[int, int]]=None, + server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None, + ignore_operation_servers: bool=False, + ssl_ca_cert: Optional[str]=None, + retries: Optional[int] = None, + *, + debug: Optional[bool] = None, + ) -> None: + """Constructor + """ + self._base_path = "https://api.codat.io" if host is None else host + """Default Base url + """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ + self.ignore_operation_servers = ignore_operation_servers + """Ignore operation servers + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.access_token = access_token + """Access token + """ + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("codat_platform") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler: Optional[FileHandler] = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + if debug is not None: + self.debug = debug + else: + self.__debug = False + """Debug switch + """ + + self.verify_ssl = True + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = ssl_ca_cert + """Set this to customize the certificate file to verify the peer. + """ + self.cert_file = None + """client certificate file + """ + self.key_file = None + """client key file + """ + self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + self.tls_server_name = None + """SSL/TLS Server Name Indication (SNI) + Set this to the SNI value expected by the server. + """ + + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. + """ + + self.proxy: Optional[str] = None + """Proxy URL + """ + self.proxy_headers = None + """Proxy headers + """ + self.safe_chars_for_path_param = '' + """Safe chars for path_param + """ + self.retries = retries + """Adding retries to override urllib3 default value 3 + """ + # Enable client side validation + self.client_side_validation = True + + self.socket_options = None + """Options to pass down to the underlying urllib3 socket + """ + + self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" + """datetime format + """ + + self.date_format = "%Y-%m-%d" + """date format + """ + + def __deepcopy__(self, memo: Dict[int, Any]) -> Self: + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name: str, value: Any) -> None: + object.__setattr__(self, name, value) + + @classmethod + def set_default(cls, default: Optional[Self]) -> None: + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = default + + @classmethod + def get_default_copy(cls) -> Self: + """Deprecated. Please use `get_default` instead. + + Deprecated. Please use `get_default` instead. + + :return: The configuration object. + """ + return cls.get_default() + + @classmethod + def get_default(cls) -> Self: + """Return the default configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration. + + :return: The configuration object. + """ + if cls._default is None: + cls._default = cls() + return cls._default + + @property + def logger_file(self) -> Optional[str]: + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value: Optional[str]) -> None: + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in self.logger.items(): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self) -> bool: + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value: bool) -> None: + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in self.logger.items(): + logger.setLevel(logging.DEBUG) + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in self.logger.items(): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self) -> str: + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value: str) -> None: + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]: + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. + :return: The token for api key authentication. + """ + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key + + return None + + def get_basic_auth_token(self) -> Optional[str]: + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') + + def auth_settings(self)-> AuthSettings: + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth: AuthSettings = {} + if 'auth_header' in self.api_key: + auth['auth_header'] = { + 'type': 'api_key', + 'in': 'header', + 'key': 'Authorization', + 'value': self.get_api_key_with_prefix( + 'auth_header', + ), + } + return auth + + def to_debug_report(self) -> str: + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: 3.0.0\n"\ + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) + + def get_host_settings(self) -> List[HostSetting]: + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + 'url': "https://api.codat.io", + 'description': "Production", + } + ] + + def get_host_from_settings( + self, + index: Optional[int], + variables: Optional[ServerVariablesT]=None, + servers: Optional[List[HostSetting]]=None, + ) -> str: + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None + :return: URL based on host settings + """ + if index is None: + return self._base_path + + variables = {} if variables is None else variables + servers = self.get_host_settings() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) + + return url + + @property + def host(self) -> str: + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value: str) -> None: + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/platform/src/codat_platform/connection_management.py b/platform/src/codat_platform/connection_management.py index 97f7f844b..60cfe3549 100644 --- a/platform/src/codat_platform/connection_management.py +++ b/platform/src/codat_platform/connection_management.py @@ -1,226 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.connection_management — re-export of the connection_management method group.""" -from .basesdk import BaseSDK -from codat_platform import utils -from codat_platform._hooks import HookContext -from codat_platform.models import errors, operations, shared -from codat_platform.types import BaseModel, OptionalNullable, UNSET -from codat_platform.utils.unmarshal_json_response import unmarshal_json_response -from typing import Any, Mapping, Optional, Union, cast -from typing_extensions import deprecated - - -class ConnectionManagement(BaseSDK): - r"""Configure UI and retrieve access tokens for authentication used by **Connections SDK**.""" - - @deprecated("""warning: ** DEPRECATED ** - The endpoint for generating company-specific connection management access tokens has been deprecated. -Codat now supports a global company access token, providing seamless access across multiple products. -Update your integration to use the global token for improved efficiency and consistency. -. Use get_access_token instead.""") - def get( - self, - *, - request: Union[ - operations.GetConnectionManagementAccessTokenRequest, - operations.GetConnectionManagementAccessTokenRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ConnectionManagementAccessToken: - r"""Get access token (old) - - The new [Get company access token](https://docs.codat.io/platform-api#/operations/get-company-access-token) endpoint replaces this endpoint and includes additional functionality. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetConnectionManagementAccessTokenRequest - ) - request = cast(operations.GetConnectionManagementAccessTokenRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connectionManagement/accessToken", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-connection-management-access-token", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response( - shared.ConnectionManagementAccessToken, http_res - ) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - @deprecated("""warning: ** DEPRECATED ** - The endpoint for generating company-specific connection management access tokens has been deprecated. -Codat now supports a global company access token, providing seamless access across multiple products. -Update your integration to use the global token for improved efficiency and consistency. -. Use get_access_token instead.""") - async def get_async( - self, - *, - request: Union[ - operations.GetConnectionManagementAccessTokenRequest, - operations.GetConnectionManagementAccessTokenRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ConnectionManagementAccessToken: - r"""Get access token (old) - - The new [Get company access token](https://docs.codat.io/platform-api#/operations/get-company-access-token) endpoint replaces this endpoint and includes additional functionality. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetConnectionManagementAccessTokenRequest - ) - request = cast(operations.GetConnectionManagementAccessTokenRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connectionManagement/accessToken", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-connection-management-access-token", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response( - shared.ConnectionManagementAccessToken, http_res - ) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_platform.api.connection_management import ConnectionManagement diff --git a/platform/src/codat_platform/connections.py b/platform/src/codat_platform/connections.py index 976470e30..0cbb67afe 100644 --- a/platform/src/codat_platform/connections.py +++ b/platform/src/codat_platform/connections.py @@ -1,1239 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.connections — re-export of the connections method group.""" -from .basesdk import BaseSDK -from codat_platform import utils -from codat_platform._hooks import HookContext -from codat_platform.models import errors, operations, shared -from codat_platform.types import BaseModel, OptionalNullable, UNSET -from codat_platform.utils.unmarshal_json_response import unmarshal_json_response -from typing import Any, Dict, Mapping, Optional, Union, cast - - -class Connections(BaseSDK): - r"""Create new and manage existing data connections for a company.""" - - def create( - self, - *, - request: Union[ - operations.CreateConnectionRequest, - operations.CreateConnectionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Create connection - - Creates a connection for the company by providing a valid `platformKey`. - - Use the [List Integrations](https://docs.codat.io/platform-api#/operations/list-integrations) endpoint to access valid platform keys. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.CreateConnectionRequest) - request = cast(operations.CreateConnectionRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/connections", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.request_body if request is not None else None, - False, - True, - "json", - Optional[operations.CreateConnectionRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def create_async( - self, - *, - request: Union[ - operations.CreateConnectionRequest, - operations.CreateConnectionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Create connection - - Creates a connection for the company by providing a valid `platformKey`. - - Use the [List Integrations](https://docs.codat.io/platform-api#/operations/list-integrations) endpoint to access valid platform keys. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.CreateConnectionRequest) - request = cast(operations.CreateConnectionRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/connections", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.request_body if request is not None else None, - False, - True, - "json", - Optional[operations.CreateConnectionRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def delete( - self, - *, - request: Union[ - operations.DeleteConnectionRequest, - operations.DeleteConnectionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Delete connection - - Revoke and remove a connection from a company. - This operation is not reversible. The end user would need to reauthorize a new data connection if you wish to view new data for this company. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DeleteConnectionRequest) - request = cast(operations.DeleteConnectionRequest, request) - - req = self._build_request( - method="DELETE", - path="/companies/{companyId}/connections/{connectionId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="delete-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def delete_async( - self, - *, - request: Union[ - operations.DeleteConnectionRequest, - operations.DeleteConnectionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Delete connection - - Revoke and remove a connection from a company. - This operation is not reversible. The end user would need to reauthorize a new data connection if you wish to view new data for this company. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DeleteConnectionRequest) - request = cast(operations.DeleteConnectionRequest, request) - - req = self._build_request_async( - method="DELETE", - path="/companies/{companyId}/connections/{connectionId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="delete-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get( - self, - *, - request: Union[ - operations.GetConnectionRequest, operations.GetConnectionRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Get connection - - Returns a specific connection for a company when valid identifiers are provided. If the identifiers are for a deleted company and/or connection, a not found response is returned. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetConnectionRequest) - request = cast(operations.GetConnectionRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections/{connectionId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_async( - self, - *, - request: Union[ - operations.GetConnectionRequest, operations.GetConnectionRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Get connection - - Returns a specific connection for a company when valid identifiers are provided. If the identifiers are for a deleted company and/or connection, a not found response is returned. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetConnectionRequest) - request = cast(operations.GetConnectionRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections/{connectionId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def list( - self, - *, - request: Union[ - operations.ListConnectionsRequest, - operations.ListConnectionsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connections: - r"""List connections - - List the connections for a company. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListConnectionsRequest) - request = cast(operations.ListConnectionsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-connections", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connections, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def list_async( - self, - *, - request: Union[ - operations.ListConnectionsRequest, - operations.ListConnectionsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connections: - r"""List connections - - List the connections for a company. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListConnectionsRequest) - request = cast(operations.ListConnectionsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-connections", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connections, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def unlink( - self, - *, - request: Union[ - operations.UnlinkConnectionRequest, - operations.UnlinkConnectionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Unlink connection - - This allows you to deauthorize a connection, without deleting it from Codat. This means you can still view any data that has previously been pulled into Codat, and also lets you re-authorize in future if your customer wishes to resume sharing their data. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UnlinkConnectionRequest) - request = cast(operations.UnlinkConnectionRequest, request) - - req = self._build_request( - method="PATCH", - path="/companies/{companyId}/connections/{connectionId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.update_connection_status if request is not None else None, - False, - True, - "json", - Optional[shared.UpdateConnectionStatus], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="unlink-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def unlink_async( - self, - *, - request: Union[ - operations.UnlinkConnectionRequest, - operations.UnlinkConnectionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Unlink connection - - This allows you to deauthorize a connection, without deleting it from Codat. This means you can still view any data that has previously been pulled into Codat, and also lets you re-authorize in future if your customer wishes to resume sharing their data. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UnlinkConnectionRequest) - request = cast(operations.UnlinkConnectionRequest, request) - - req = self._build_request_async( - method="PATCH", - path="/companies/{companyId}/connections/{connectionId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.update_connection_status if request is not None else None, - False, - True, - "json", - Optional[shared.UpdateConnectionStatus], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="unlink-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def update_authorization( - self, - *, - request: Union[ - operations.UpdateConnectionAuthorizationRequest, - operations.UpdateConnectionAuthorizationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Update authorization - - Update data connection's authorization. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.UpdateConnectionAuthorizationRequest - ) - request = cast(operations.UpdateConnectionAuthorizationRequest, request) - - req = self._build_request( - method="PUT", - path="/companies/{companyId}/connections/{connectionId}/authorization", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.request_body if request is not None else None, - False, - True, - "json", - Optional[Dict[str, str]], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-connection-authorization", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def update_authorization_async( - self, - *, - request: Union[ - operations.UpdateConnectionAuthorizationRequest, - operations.UpdateConnectionAuthorizationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Update authorization - - Update data connection's authorization. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.UpdateConnectionAuthorizationRequest - ) - request = cast(operations.UpdateConnectionAuthorizationRequest, request) - - req = self._build_request_async( - method="PUT", - path="/companies/{companyId}/connections/{connectionId}/authorization", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.request_body if request is not None else None, - False, - True, - "json", - Optional[Dict[str, str]], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-connection-authorization", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_platform.api.connections import Connections diff --git a/platform/src/codat_platform/cors.py b/platform/src/codat_platform/cors.py index 1c4a5e749..f9530b010 100644 --- a/platform/src/codat_platform/cors.py +++ b/platform/src/codat_platform/cors.py @@ -1,434 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.cors — re-export of the cors method group.""" -from .basesdk import BaseSDK -from codat_platform import utils -from codat_platform._hooks import HookContext -from codat_platform.models import errors, shared -from codat_platform.types import BaseModel, OptionalNullable, UNSET -from codat_platform.utils.unmarshal_json_response import unmarshal_json_response -from typing import Any, Mapping, Optional, Union, cast -from typing_extensions import deprecated - - -class Cors(BaseSDK): - @deprecated("""warning: ** DEPRECATED ** - The new [Get CORS settings](https://docs.codat.io/platform-api#/operations/get-cors-settings) endpoint replaces this endpoint and includes additional functionality. -Update your integrations to use the new path `/corsSettings` as the existing route will be removed in a future release. -. Use get instead.""") - def get( - self, - *, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ConnectionManagementAllowedOrigins: - r"""Get CORS settings (old) - - The *Get CORS settings* endpoint returns the allowed origins (i.e. your domains) you want to allow cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)) with Codat. - - Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. - - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - req = self._build_request( - method="GET", - path="/connectionManagement/corsSettings", - base_url=base_url, - url_variables=url_variables, - request=None, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-connection-management-cors-settings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response( - shared.ConnectionManagementAllowedOrigins, http_res - ) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - @deprecated("""warning: ** DEPRECATED ** - The new [Get CORS settings](https://docs.codat.io/platform-api#/operations/get-cors-settings) endpoint replaces this endpoint and includes additional functionality. -Update your integrations to use the new path `/corsSettings` as the existing route will be removed in a future release. -. Use get instead.""") - async def get_async( - self, - *, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ConnectionManagementAllowedOrigins: - r"""Get CORS settings (old) - - The *Get CORS settings* endpoint returns the allowed origins (i.e. your domains) you want to allow cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)) with Codat. - - Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. - - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - req = self._build_request_async( - method="GET", - path="/connectionManagement/corsSettings", - base_url=base_url, - url_variables=url_variables, - request=None, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-connection-management-cors-settings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response( - shared.ConnectionManagementAllowedOrigins, http_res - ) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - @deprecated("""warning: ** DEPRECATED ** - The new [Set CORS settings](https://docs.codat.io/platform-api#/operations/set-cors-settings) endpoint replaces this endpoint and includes additional functionality. -Update your integrations to use the new path `/corsSettings` as the existing route will be removed in a future release. -. Use set instead.""") - def set( - self, - *, - request: Optional[ - Union[ - shared.ConnectionManagementAllowedOrigins, - shared.ConnectionManagementAllowedOriginsTypedDict, - ] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ConnectionManagementAllowedOrigins: - r"""Set CORS settings (old) - - The *Set CORS settings* endpoint allows you to register allowed origins (i.e. your domains) for use in cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)). - - Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, Optional[shared.ConnectionManagementAllowedOrigins] - ) - request = cast(Optional[shared.ConnectionManagementAllowedOrigins], request) - - req = self._build_request( - method="POST", - path="/connectionManagement/corsSettings", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, - False, - True, - "json", - Optional[shared.ConnectionManagementAllowedOrigins], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="set-connection-management-cors-settings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response( - shared.ConnectionManagementAllowedOrigins, http_res - ) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - @deprecated("""warning: ** DEPRECATED ** - The new [Set CORS settings](https://docs.codat.io/platform-api#/operations/set-cors-settings) endpoint replaces this endpoint and includes additional functionality. -Update your integrations to use the new path `/corsSettings` as the existing route will be removed in a future release. -. Use set instead.""") - async def set_async( - self, - *, - request: Optional[ - Union[ - shared.ConnectionManagementAllowedOrigins, - shared.ConnectionManagementAllowedOriginsTypedDict, - ] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ConnectionManagementAllowedOrigins: - r"""Set CORS settings (old) - - The *Set CORS settings* endpoint allows you to register allowed origins (i.e. your domains) for use in cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)). - - Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, Optional[shared.ConnectionManagementAllowedOrigins] - ) - request = cast(Optional[shared.ConnectionManagementAllowedOrigins], request) - - req = self._build_request_async( - method="POST", - path="/connectionManagement/corsSettings", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, - False, - True, - "json", - Optional[shared.ConnectionManagementAllowedOrigins], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="set-connection-management-cors-settings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response( - shared.ConnectionManagementAllowedOrigins, http_res - ) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_platform.api.cors import Cors diff --git a/platform/src/codat_platform/custom_data_type.py b/platform/src/codat_platform/custom_data_type.py index 0de60ae81..f8cc6cc38 100644 --- a/platform/src/codat_platform/custom_data_type.py +++ b/platform/src/codat_platform/custom_data_type.py @@ -1,855 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.custom_data_type — re-export of the custom_data_type method group.""" -from .basesdk import BaseSDK -from codat_platform import utils -from codat_platform._hooks import HookContext -from codat_platform.models import errors, operations, shared -from codat_platform.types import BaseModel, OptionalNullable, UNSET -from codat_platform.utils.unmarshal_json_response import unmarshal_json_response -from typing import Any, Mapping, Optional, Union, cast - - -class CustomDataType(BaseSDK): - r"""Configure and pull additional data types that are not included in Codat's standardized data model.""" - - def configure( - self, - *, - request: Union[ - operations.ConfigureCustomDataTypeRequest, - operations.ConfigureCustomDataTypeRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CustomDataTypeConfiguration: - r"""Configure custom data type - - The *Configure custom data type* endpoint allows you to maintain or change the configuration required to return a custom data type for a specific integration. - - A [custom data type](https://docs.codat.io/using-the-api/custom-data) is an additional data type you can create that is not included in Codat's standardized data model. - - ### Tips and traps - - - You can only configure a single custom data type for a single platform at a time. Use the endpoint multiple times if you need to configure it for multiple platforms. - - - You can only indicate a single data source for each customer data type. - - - Make your custom configuration as similar as possible to our standard data types so you can interact with them in exactly the same way. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.ConfigureCustomDataTypeRequest - ) - request = cast(operations.ConfigureCustomDataTypeRequest, request) - - req = self._build_request( - method="PUT", - path="/integrations/{platformKey}/dataTypes/custom/{customDataIdentifier}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.custom_data_type_configuration if request is not None else None, - False, - True, - "json", - Optional[shared.CustomDataTypeConfiguration], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="configure-custom-data-type", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.CustomDataTypeConfiguration, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def configure_async( - self, - *, - request: Union[ - operations.ConfigureCustomDataTypeRequest, - operations.ConfigureCustomDataTypeRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CustomDataTypeConfiguration: - r"""Configure custom data type - - The *Configure custom data type* endpoint allows you to maintain or change the configuration required to return a custom data type for a specific integration. - - A [custom data type](https://docs.codat.io/using-the-api/custom-data) is an additional data type you can create that is not included in Codat's standardized data model. - - ### Tips and traps - - - You can only configure a single custom data type for a single platform at a time. Use the endpoint multiple times if you need to configure it for multiple platforms. - - - You can only indicate a single data source for each customer data type. - - - Make your custom configuration as similar as possible to our standard data types so you can interact with them in exactly the same way. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.ConfigureCustomDataTypeRequest - ) - request = cast(operations.ConfigureCustomDataTypeRequest, request) - - req = self._build_request_async( - method="PUT", - path="/integrations/{platformKey}/dataTypes/custom/{customDataIdentifier}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.custom_data_type_configuration if request is not None else None, - False, - True, - "json", - Optional[shared.CustomDataTypeConfiguration], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="configure-custom-data-type", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.CustomDataTypeConfiguration, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get_configuration( - self, - *, - request: Union[ - operations.GetCustomDataTypeConfigurationRequest, - operations.GetCustomDataTypeConfigurationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CustomDataTypeRecords: - r"""Get custom data configuration - - The *Get custom data configuration* endpoint returns existing configuration details for the specified custom data type and integration pair you previously configured. - - A [custom data type](https://docs.codat.io/using-the-api/custom-data) is an additional data type you can create that is not included in Codat's standardized data model. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetCustomDataTypeConfigurationRequest - ) - request = cast(operations.GetCustomDataTypeConfigurationRequest, request) - - req = self._build_request( - method="GET", - path="/integrations/{platformKey}/dataTypes/custom/{customDataIdentifier}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-custom-data-type-configuration", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.CustomDataTypeRecords, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_configuration_async( - self, - *, - request: Union[ - operations.GetCustomDataTypeConfigurationRequest, - operations.GetCustomDataTypeConfigurationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CustomDataTypeRecords: - r"""Get custom data configuration - - The *Get custom data configuration* endpoint returns existing configuration details for the specified custom data type and integration pair you previously configured. - - A [custom data type](https://docs.codat.io/using-the-api/custom-data) is an additional data type you can create that is not included in Codat's standardized data model. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetCustomDataTypeConfigurationRequest - ) - request = cast(operations.GetCustomDataTypeConfigurationRequest, request) - - req = self._build_request_async( - method="GET", - path="/integrations/{platformKey}/dataTypes/custom/{customDataIdentifier}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-custom-data-type-configuration", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.CustomDataTypeRecords, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def list( - self, - *, - request: Union[ - operations.ListCustomDataTypeRecordsRequest, - operations.ListCustomDataTypeRecordsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CustomDataTypeRecords: - r"""List custom data type records - - The *List custom data type records* endpoint returns a paginated list of records pulled for the specified custom data type you previously configured. - - A [custom data type](https://docs.codat.io/using-the-api/custom-data) is an additional data type you can create that is not included in Codat's standardized data model.s endpoint returns a paginated list of records whose schema is defined [Configure custom data type](https://docs.codat.io/platform-api#/operations/configure-custom-data-type) - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.ListCustomDataTypeRecordsRequest - ) - request = cast(operations.ListCustomDataTypeRecordsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/data/custom/{customDataIdentifier}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-custom-data-type-records", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.CustomDataTypeRecords, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "429", "451"], - "application/json", - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def list_async( - self, - *, - request: Union[ - operations.ListCustomDataTypeRecordsRequest, - operations.ListCustomDataTypeRecordsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CustomDataTypeRecords: - r"""List custom data type records - - The *List custom data type records* endpoint returns a paginated list of records pulled for the specified custom data type you previously configured. - - A [custom data type](https://docs.codat.io/using-the-api/custom-data) is an additional data type you can create that is not included in Codat's standardized data model.s endpoint returns a paginated list of records whose schema is defined [Configure custom data type](https://docs.codat.io/platform-api#/operations/configure-custom-data-type) - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.ListCustomDataTypeRecordsRequest - ) - request = cast(operations.ListCustomDataTypeRecordsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/data/custom/{customDataIdentifier}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-custom-data-type-records", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.CustomDataTypeRecords, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "429", "451"], - "application/json", - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def refresh( - self, - *, - request: Union[ - operations.RefreshCustomDataTypeRequest, - operations.RefreshCustomDataTypeRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperation: - r"""Refresh custom data type - - The *Refresh custom data type* endpoint refreshes the specified custom data type for a given company. This is an asynchronous operation that will sync updated data from the linked integration into Codat for you to view. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.RefreshCustomDataTypeRequest) - request = cast(operations.RefreshCustomDataTypeRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/data/queue/custom/{customDataIdentifier}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="refresh-custom-data-type", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PullOperation, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429", "451"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def refresh_async( - self, - *, - request: Union[ - operations.RefreshCustomDataTypeRequest, - operations.RefreshCustomDataTypeRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperation: - r"""Refresh custom data type - - The *Refresh custom data type* endpoint refreshes the specified custom data type for a given company. This is an asynchronous operation that will sync updated data from the linked integration into Codat for you to view. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.RefreshCustomDataTypeRequest) - request = cast(operations.RefreshCustomDataTypeRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/data/queue/custom/{customDataIdentifier}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="refresh-custom-data-type", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PullOperation, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429", "451"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_platform.api.custom_data_type import CustomDataType diff --git a/platform/src/codat_platform/exceptions.py b/platform/src/codat_platform/exceptions.py new file mode 100644 index 000000000..01cad3473 --- /dev/null +++ b/platform/src/codat_platform/exceptions.py @@ -0,0 +1,200 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from typing import Any, Optional +from typing_extensions import Self + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None) -> None: + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + + def __init__( + self, + status=None, + reason=None, + http_resp=None, + *, + body: Optional[str] = None, + data: Optional[Any] = None, + ) -> None: + self.status = status + self.reason = reason + self.body = body + self.data = data + self.headers = None + + if http_resp: + if self.status is None: + self.status = http_resp.status + if self.reason is None: + self.reason = http_resp.reason + if self.body is None: + try: + self.body = http_resp.data.decode('utf-8') + except Exception: + pass + self.headers = http_resp.getheaders() + + @classmethod + def from_response( + cls, + *, + http_resp, + body: Optional[str], + data: Optional[Any], + ) -> Self: + if http_resp.status == 400: + raise BadRequestException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 401: + raise UnauthorizedException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 403: + raise ForbiddenException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 404: + raise NotFoundException(http_resp=http_resp, body=body, data=data) + + if 500 <= http_resp.status <= 599: + raise ServiceException(http_resp=http_resp, body=body, data=data) + raise ApiException(http_resp=http_resp, body=body, data=data) + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.data or self.body: + error_message += "HTTP response body: {0}\n".format(self.data or self.body) + + return error_message + + +class BadRequestException(ApiException): + pass + + +class NotFoundException(ApiException): + pass + + +class UnauthorizedException(ApiException): + pass + + +class ForbiddenException(ApiException): + pass + + +class ServiceException(ApiException): + pass + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/platform/src/codat_platform/integrations.py b/platform/src/codat_platform/integrations.py index 3d24eb82c..36574194a 100644 --- a/platform/src/codat_platform/integrations.py +++ b/platform/src/codat_platform/integrations.py @@ -1,603 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.integrations — re-export of the integrations method group.""" -from .basesdk import BaseSDK -from codat_platform import utils -from codat_platform._hooks import HookContext -from codat_platform.models import errors, operations, shared -from codat_platform.types import BaseModel, OptionalNullable, UNSET -from codat_platform.utils.unmarshal_json_response import unmarshal_json_response -from typing import Any, Mapping, Optional, Union, cast - - -class Integrations(BaseSDK): - r"""Get a list of integrations supported by Codat and their logos.""" - - def get( - self, - *, - request: Union[ - operations.GetIntegrationRequest, operations.GetIntegrationRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Integration: - r"""Get integration - - Get single integration, by platformKey - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetIntegrationRequest) - request = cast(operations.GetIntegrationRequest, request) - - req = self._build_request( - method="GET", - path="/integrations/{platformKey}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-integration", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Integration, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_async( - self, - *, - request: Union[ - operations.GetIntegrationRequest, operations.GetIntegrationRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Integration: - r"""Get integration - - Get single integration, by platformKey - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetIntegrationRequest) - request = cast(operations.GetIntegrationRequest, request) - - req = self._build_request_async( - method="GET", - path="/integrations/{platformKey}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-integration", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Integration, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get_branding( - self, - *, - request: Union[ - operations.GetIntegrationsBrandingRequest, - operations.GetIntegrationsBrandingRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Branding: - r"""Get branding - - Get branding for platform. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetIntegrationsBrandingRequest - ) - request = cast(operations.GetIntegrationsBrandingRequest, request) - - req = self._build_request( - method="GET", - path="/integrations/{platformKey}/branding", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-integrations-branding", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Branding, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_branding_async( - self, - *, - request: Union[ - operations.GetIntegrationsBrandingRequest, - operations.GetIntegrationsBrandingRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Branding: - r"""Get branding - - Get branding for platform. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetIntegrationsBrandingRequest - ) - request = cast(operations.GetIntegrationsBrandingRequest, request) - - req = self._build_request_async( - method="GET", - path="/integrations/{platformKey}/branding", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-integrations-branding", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Branding, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def list( - self, - *, - request: Union[ - operations.ListIntegrationsRequest, - operations.ListIntegrationsRequestTypedDict, - ] = operations.ListIntegrationsRequest(), - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Integrations: - r"""List integrations - - List your available integrations - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListIntegrationsRequest) - request = cast(operations.ListIntegrationsRequest, request) - - req = self._build_request( - method="GET", - path="/integrations", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-integrations", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Integrations, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def list_async( - self, - *, - request: Union[ - operations.ListIntegrationsRequest, - operations.ListIntegrationsRequestTypedDict, - ] = operations.ListIntegrationsRequest(), - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Integrations: - r"""List integrations - - List your available integrations - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListIntegrationsRequest) - request = cast(operations.ListIntegrationsRequest, request) - - req = self._build_request_async( - method="GET", - path="/integrations", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-integrations", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Integrations, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_platform.api.integrations import Integrations diff --git a/platform/src/codat_platform/models/__init__.py b/platform/src/codat_platform/models/__init__.py index d78064cca..2a69ea575 100644 --- a/platform/src/codat_platform/models/__init__.py +++ b/platform/src/codat_platform/models/__init__.py @@ -1,23 +1,113 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from typing import Any, TYPE_CHECKING +# flake8: noqa +""" + Platform API -from codat_platform.utils.dynamic_imports import lazy_getattr, lazy_dir + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -if TYPE_CHECKING: - from . import errors, operations, shared + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) -# package + Do not edit the class manually. +""" # noqa: E501 -_sub_packages = ["errors", "operations", "shared"] - - -def __getattr__(attr_name: str) -> Any: - return lazy_getattr( - attr_name, package=__package__, dynamic_imports={}, sub_packages=_sub_packages - ) - - -def __dir__(): - return lazy_dir(dynamic_imports={}, sub_packages=_sub_packages) +# import models into model package +from codat_platform.models.access_token import AccessToken +from codat_platform.models.shared.apikeydetails import APIKeyDetails +from codat_platform.models.shared.apikeydetails import APIKeyDetails as ApiKeyDetails +from codat_platform.models.shared.apikeys import APIKeys +from codat_platform.models.shared.apikeys import APIKeys as ApiKeys +from codat_platform.models.shared.branding import Branding +from codat_platform.models.shared.brandingbutton import BrandingButton +from codat_platform.models.shared.brandingimage import BrandingImage +from codat_platform.models.shared.brandinglogo import BrandingLogo +from codat_platform.models.shared.clientratelimitwebhook import ClientRateLimitWebhook +from codat_platform.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayload +from codat_platform.models.shared.companies import Companies +from codat_platform.models.shared.company import Company +from codat_platform.models.shared.companyaccesstoken import CompanyAccessToken +from codat_platform.models.shared.companydetails import CompanyDetails +from codat_platform.models.company_product_webhook import CompanyProductWebhook +from codat_platform.models.company_product_webhook_payload import CompanyProductWebhookPayload +from codat_platform.models.shared.companyreference import CompanyReference +from codat_platform.models.company_reference_links import CompanyReferenceLinks +from codat_platform.models.shared.companyrequestbody import CompanyRequestBody +from codat_platform.models.shared.companysyncsettings import CompanySyncSettings +from codat_platform.models.shared.companyupdaterequest import CompanyUpdateRequest +from codat_platform.models.shared.companywebhook import CompanyWebhook +from codat_platform.models.shared.connection import Connection +from codat_platform.models.shared.connectionmanagementaccesstoken import ConnectionManagementAccessToken +from codat_platform.models.shared.connectionmanagementallowedorigins import ConnectionManagementAllowedOrigins +from codat_platform.models.shared.connectionwebhook import ConnectionWebhook +from codat_platform.models.shared.connectionwebhookpayload import ConnectionWebhookPayload +from codat_platform.models.shared.connections import Connections +from codat_platform.models.shared.createapikey import CreateAPIKey +from codat_platform.models.shared.createapikey import CreateAPIKey as CreateApiKey +from codat_platform.models.create_connection_request import CreateConnectionRequest +from codat_platform.models.shared.customdatatypeconfiguration import CustomDataTypeConfiguration +from codat_platform.models.shared.customdatatyperecord import CustomDataTypeRecord +from codat_platform.models.shared.customdatatyperecords import CustomDataTypeRecords +from codat_platform.models.shared.dataconnectionerror import DataConnectionError +from codat_platform.models.shared.dataconnectionstatus import DataConnectionStatus +from codat_platform.models.shared.datastatus import DataStatus +from codat_platform.models.shared.datastatuses import DataStatuses +from codat_platform.models.shared.datatype import DataType +from codat_platform.models.shared.datatypefeature import DataTypeFeature +from codat_platform.models.shared.datatypereadsummary import DataTypeReadSummary +from codat_platform.models.shared.datatypewritewebhook import DataTypeWriteWebhook +from codat_platform.models.shared.datatypewritewebhookpayload import DataTypeWriteWebhookPayload +from codat_platform.models.shared.datatypewritewebhookrecord import DataTypeWriteWebhookRecord +from codat_platform.models.shared.errormessage import ErrorMessage +from codat_platform.models.shared.errorvalidation import ErrorValidation +from codat_platform.models.shared.errorvalidationitem import ErrorValidationItem +from codat_platform.models.shared.featurestate import FeatureState +from codat_platform.models.shared.featuretype import FeatureType +from codat_platform.models.shared.halref import HalRef +from codat_platform.models.shared.imagereference import ImageReference +from codat_platform.models.shared.integration import Integration +from codat_platform.models.shared.integrations import Integrations +from codat_platform.models.shared.issue import Issue +from codat_platform.models.issue_links import IssueLinks +from codat_platform.models.shared.links import Links +from codat_platform.models.modified_date import ModifiedDate +from codat_platform.models.paging_info import PagingInfo +from codat_platform.models.shared.profile import Profile +from codat_platform.models.shared.pulloperation import PullOperation +from codat_platform.models.shared.pulloperations import PullOperations +from codat_platform.models.shared.pushchangetype import PushChangeType +from codat_platform.models.shared.pushfieldvalidation import PushFieldValidation +from codat_platform.models.shared.pushoperation import PushOperation +from codat_platform.models.shared.pushoperationchange import PushOperationChange +from codat_platform.models.shared.pushoperationref import PushOperationRef +from codat_platform.models.shared.pushoperationstatus import PushOperationStatus +from codat_platform.models.shared.pushoperations import PushOperations +from codat_platform.models.shared.pushoption import PushOption +from codat_platform.models.shared.pushoptionchoice import PushOptionChoice +from codat_platform.models.shared.pushoptionproperty import PushOptionProperty +from codat_platform.models.shared.pushoptiontype import PushOptionType +from codat_platform.models.shared.pushvalidationinfo import PushValidationInfo +from codat_platform.models.shared.readcompletedwebhook import ReadCompletedWebhook +from codat_platform.models.shared.readcompletedwebhookpayload import ReadCompletedWebhookPayload +from codat_platform.models.refresh_product_data_request import RefreshProductDataRequest +from codat_platform.models.set_company_sync_settings_request import SetCompanySyncSettingsRequest +from codat_platform.models.shared.sourcetype import SourceType +from codat_platform.models.shared.status import Status +from codat_platform.models.shared.supplementaldataconfiguration import SupplementalDataConfiguration +from codat_platform.models.supplemental_data_source_configuration import SupplementalDataSourceConfiguration +from codat_platform.models.shared.supportedfeature import SupportedFeature +from codat_platform.models.shared.syncsetting import SyncSetting +from codat_platform.models.shared.syncsettings import SyncSettings +from codat_platform.models.shared.updateconnectionstatus import UpdateConnectionStatus +from codat_platform.models.update_profile_sync_settings_request import UpdateProfileSyncSettingsRequest +from codat_platform.models.shared.validation import Validation +from codat_platform.models.shared.validationitem import ValidationItem +from codat_platform.models.shared.validationresult import ValidationResult +from codat_platform.models.shared.webhookconsumer import WebhookConsumer +from codat_platform.models.shared.webhookconsumerprototype import WebhookConsumerPrototype +from codat_platform.models.shared.webhookconsumers import WebhookConsumers +from codat_platform.models.webhook_zapier_key import WebhookZapierKey +from codat_platform.models.shared.writestatus import WriteStatus +from codat_platform.models.shared.writetype import WriteType diff --git a/platform/src/codat_platform/models/_compat/__init__.py b/platform/src/codat_platform/models/_compat/__init__.py new file mode 100644 index 000000000..70271e525 --- /dev/null +++ b/platform/src/codat_platform/models/_compat/__init__.py @@ -0,0 +1,3 @@ +"""Leaf modules holding Speakeasy-name compat enums. Nothing here imports from the +package, so a flat model can import these without triggering models/shared/__init__ +(which re-exports flat models and would form an import cycle).""" diff --git a/platform/src/codat_platform/models/_compat/schema_datatype.py b/platform/src/codat_platform/models/_compat/schema_datatype.py new file mode 100644 index 000000000..1d7d3b5ca --- /dev/null +++ b/platform/src/codat_platform/models/_compat/schema_datatype.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from enum import Enum + + +class SchemaDataType(str, Enum): + """Speakeasy-name compat for DataTypes (matched by value set).""" + ACCOUNT_TRANSACTIONS = 'accountTransactions' + BALANCE_SHEET = 'balanceSheet' + BANK_ACCOUNTS = 'bankAccounts' + BANK_TRANSACTIONS = 'bankTransactions' + BILL_CREDIT_NOTES = 'billCreditNotes' + BILL_PAYMENTS = 'billPayments' + BILLS = 'bills' + CASH_FLOW_STATEMENT = 'cashFlowStatement' + CHART_OF_ACCOUNTS = 'chartOfAccounts' + COMPANY = 'company' + CREDIT_NOTES = 'creditNotes' + CUSTOMERS = 'customers' + DIRECT_COSTS = 'directCosts' + DIRECT_INCOMES = 'directIncomes' + INVOICES = 'invoices' + ITEM_RECEIPTS = 'itemReceipts' + ITEMS = 'items' + JOURNAL_ENTRIES = 'journalEntries' + JOURNALS = 'journals' + PAYMENT_METHODS = 'paymentMethods' + PAYMENTS = 'payments' + PROFIT_AND_LOSS = 'profitAndLoss' + PURCHASE_ORDERS = 'purchaseOrders' + SALES_ORDERS = 'salesOrders' + SUPPLIERS = 'suppliers' + TAX_RATES = 'taxRates' + TRACKING_CATEGORIES = 'trackingCategories' + TRANSFERS = 'transfers' + BANKING_ACCOUNT_BALANCES = 'banking-accountBalances' + BANKING_ACCOUNTS = 'banking-accounts' + BANKING_TRANSACTION_CATEGORIES = 'banking-transactionCategories' + BANKING_TRANSACTIONS = 'banking-transactions' + COMMERCE_COMPANY_INFO = 'commerce-companyInfo' + COMMERCE_CUSTOMERS = 'commerce-customers' + COMMERCE_DISPUTES = 'commerce-disputes' + COMMERCE_LOCATIONS = 'commerce-locations' + COMMERCE_ORDERS = 'commerce-orders' + COMMERCE_PAYMENT_METHODS = 'commerce-paymentMethods' + COMMERCE_PAYMENTS = 'commerce-payments' + COMMERCE_PRODUCT_CATEGORIES = 'commerce-productCategories' + COMMERCE_PRODUCTS = 'commerce-products' + COMMERCE_TAX_COMPONENTS = 'commerce-taxComponents' + COMMERCE_TRANSACTIONS = 'commerce-transactions' diff --git a/platform/src/codat_platform/models/access_token.py b/platform/src/codat_platform/models/access_token.py new file mode 100644 index 000000000..6226253c1 --- /dev/null +++ b/platform/src/codat_platform/models/access_token.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class AccessToken(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + AccessToken + """ # noqa: E501 + expires_in: int = Field(description="The number of seconds until the access token expires.", alias="expiresIn") + access_token: str = Field(description="The access token for the company.", alias="accessToken") + token_type: str = Field(description="The type of token.", alias="tokenType") + __properties: ClassVar[List[str]] = ["expiresIn", "accessToken", "tokenType"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AccessToken from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AccessToken from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "expiresIn": obj.get("expiresIn"), + "accessToken": obj.get("accessToken"), + "tokenType": obj.get("tokenType") + }) + return _obj + + + + + +class AccessTokenTypedDict(TypedDict): + """TypedDict variant of AccessToken, for dict-literal request/response inputs.""" + expires_in: NotRequired[int] + access_token: NotRequired[str] + token_type: NotRequired[str] diff --git a/platform/src/codat_platform/models/company_product_webhook.py b/platform/src/codat_platform/models/company_product_webhook.py new file mode 100644 index 000000000..acba17266 --- /dev/null +++ b/platform/src/codat_platform/models/company_product_webhook.py @@ -0,0 +1,112 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.company_product_webhook_payload import CompanyProductWebhookPayload, CompanyProductWebhookPayloadTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class CompanyProductWebhook(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + CompanyProductWebhook + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the event.") + event_type: Optional[str] = Field(default=None, description="The type of event.", alias="eventType") + generated_date: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="generatedDate") + payload: Optional[CompanyProductWebhookPayload] = None + __properties: ClassVar[List[str]] = ["id", "eventType", "generatedDate", "payload"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyProductWebhook from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of payload + if self.payload: + _dict['payload'] = self.payload.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyProductWebhook from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "eventType": obj.get("eventType"), + "generatedDate": obj.get("generatedDate"), + "payload": CompanyProductWebhookPayload.from_dict(obj["payload"]) if obj.get("payload") is not None else None + }) + return _obj + + + + + +class CompanyProductWebhookTypedDict(TypedDict): + """TypedDict variant of CompanyProductWebhook, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + event_type: NotRequired[Optional[str]] + generated_date: NotRequired[Optional[str]] + payload: NotRequired[Optional[CompanyProductWebhookPayloadTypedDict]] diff --git a/platform/src/codat_platform/models/company_product_webhook_payload.py b/platform/src/codat_platform/models/company_product_webhook_payload.py new file mode 100644 index 000000000..6d2881943 --- /dev/null +++ b/platform/src/codat_platform/models/company_product_webhook_payload.py @@ -0,0 +1,114 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class CompanyProductWebhookPayload(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + CompanyProductWebhookPayload + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the company the product change applies to.") + name: Optional[str] = Field(default=None, description="Name of the company.") + description: Optional[str] = Field(default=None, description="A description of the property.") + product_id: Optional[str] = Field(default=None, description="Unique identifier of the product that was added to or removed from the company.", alias="productId") + product_name: Optional[str] = Field(default=None, description="Name of the product that was added to or removed from the company.", alias="productName") + products: Optional[List[str]] = Field(default=None, description="The full list of products currently enabled for the company.") + __properties: ClassVar[List[str]] = ["id", "name", "description", "productId", "productName", "products"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyProductWebhookPayload from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyProductWebhookPayload from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "description": obj.get("description"), + "productId": obj.get("productId"), + "productName": obj.get("productName"), + "products": obj.get("products") + }) + return _obj + + + + + +class CompanyProductWebhookPayloadTypedDict(TypedDict): + """TypedDict variant of CompanyProductWebhookPayload, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + description: NotRequired[Optional[str]] + product_id: NotRequired[Optional[str]] + product_name: NotRequired[Optional[str]] + products: NotRequired[Optional[List[str]]] diff --git a/platform/src/codat_platform/models/company_reference_links.py b/platform/src/codat_platform/models/company_reference_links.py new file mode 100644 index 000000000..f446a7920 --- /dev/null +++ b/platform/src/codat_platform/models/company_reference_links.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class CompanyReferenceLinks(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + A collection of links for the company. + """ # noqa: E501 + portal: Optional[str] = Field(default=None, description="Link to the company page in the portal.") + __properties: ClassVar[List[str]] = ["portal"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyReferenceLinks from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyReferenceLinks from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "portal": obj.get("portal") + }) + return _obj + + + + + +class CompanyReferenceLinksTypedDict(TypedDict): + """TypedDict variant of CompanyReferenceLinks, for dict-literal request/response inputs.""" + portal: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/content.py b/platform/src/codat_platform/models/content.py new file mode 100644 index 000000000..6ede5c467 --- /dev/null +++ b/platform/src/codat_platform/models/content.py @@ -0,0 +1,27 @@ +"""Freeform content object. Synthesized to match Speakeasy's shared surface.""" +from __future__ import annotations +from typing import Optional +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing_extensions import NotRequired, TypedDict + + +class ContentTypedDict(TypedDict): + pass + + +class Content(BaseModel): + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + def to_dict(self): + return self.model_dump(by_alias=True, exclude_none=True) + + @classmethod + def from_dict(cls, obj): + return cls.model_validate(obj) if obj is not None else None + + pass + + model_config = ConfigDict(populate_by_name=True, extra="allow", protected_namespaces=()) diff --git a/platform/src/codat_platform/models/create_connection_request.py b/platform/src/codat_platform/models/create_connection_request.py new file mode 100644 index 000000000..829942ae2 --- /dev/null +++ b/platform/src/codat_platform/models/create_connection_request.py @@ -0,0 +1,110 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from typing import Optional, Set +from typing_extensions import Self + +class CreateConnectionRequest(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + CreateConnectionRequest + """ # noqa: E501 + platform_key: Optional[str] = Field(default=None, description="A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys.", alias="platformKey") + __properties: ClassVar[List[str]] = ["platformKey"] + + @field_validator('platform_key') + def platform_key_validate_regular_expression(cls, value): + """Validates the regular expression""" + if value is None: + return value + + if not re.match(r"[a-z]{4}", value): + raise ValueError(r"must validate the regular expression /[a-z]{4}/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CreateConnectionRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateConnectionRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "platformKey": obj.get("platformKey") + }) + return _obj + + + + + +class CreateConnectionRequestTypedDict(TypedDict): + """TypedDict variant of CreateConnectionRequest, for dict-literal request/response inputs.""" + platform_key: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/current_status.py b/platform/src/codat_platform/models/current_status.py new file mode 100644 index 000000000..5f023c517 --- /dev/null +++ b/platform/src/codat_platform/models/current_status.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from enum import Enum + + +class CurrentStatus(str, Enum): + """CurrentStatus enum (lifted from inline OAS enum).""" + INITIAL = 'Initial' + QUEUED = 'Queued' + FETCHING = 'Fetching' + MAP_QUEUED = 'MapQueued' + MAPPING = 'Mapping' + COMPLETE = 'Complete' + FETCH_ERROR = 'FetchError' + MAP_ERROR = 'MapError' + INTERNAL_ERROR = 'InternalError' + PROCESSING_QUEUED = 'ProcessingQueued' + PROCESSING = 'Processing' + PROCESSING_ERROR = 'ProcessingError' + VALIDATION_QUEUED = 'ValidationQueued' + VALIDATING = 'Validating' + VALIDATION_ERROR = 'ValidationError' + AUTH_ERROR = 'AuthError' + CANCELLED = 'Cancelled' + NOT_SUPPORTED = 'NotSupported' + RATE_LIMIT_ERROR = 'RateLimitError' + PERMISSIONS_ERROR = 'PermissionsError' + PREREQUISITE_NOT_MET = 'PrerequisiteNotMet' diff --git a/platform/src/codat_platform/models/data_types.py b/platform/src/codat_platform/models/data_types.py new file mode 100644 index 000000000..734060127 --- /dev/null +++ b/platform/src/codat_platform/models/data_types.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from enum import Enum + + +class DataTypes(str, Enum): + """DataTypes enum (lifted from inline OAS enum).""" + ACCOUNT_TRANSACTIONS = 'accountTransactions' + BALANCE_SHEET = 'balanceSheet' + BANK_ACCOUNTS = 'bankAccounts' + BANK_TRANSACTIONS = 'bankTransactions' + BILL_CREDIT_NOTES = 'billCreditNotes' + BILL_PAYMENTS = 'billPayments' + BILLS = 'bills' + CASH_FLOW_STATEMENT = 'cashFlowStatement' + CHART_OF_ACCOUNTS = 'chartOfAccounts' + COMPANY = 'company' + CREDIT_NOTES = 'creditNotes' + CUSTOMERS = 'customers' + DIRECT_COSTS = 'directCosts' + DIRECT_INCOMES = 'directIncomes' + INVOICES = 'invoices' + ITEM_RECEIPTS = 'itemReceipts' + ITEMS = 'items' + JOURNAL_ENTRIES = 'journalEntries' + JOURNALS = 'journals' + PAYMENT_METHODS = 'paymentMethods' + PAYMENTS = 'payments' + PROFIT_AND_LOSS = 'profitAndLoss' + PURCHASE_ORDERS = 'purchaseOrders' + SALES_ORDERS = 'salesOrders' + SUPPLIERS = 'suppliers' + TAX_RATES = 'taxRates' + TRACKING_CATEGORIES = 'trackingCategories' + TRANSFERS = 'transfers' + BANKING_ACCOUNT_BALANCES = 'banking-accountBalances' + BANKING_ACCOUNTS = 'banking-accounts' + BANKING_TRANSACTION_CATEGORIES = 'banking-transactionCategories' + BANKING_TRANSACTIONS = 'banking-transactions' + COMMERCE_COMPANY_INFO = 'commerce-companyInfo' + COMMERCE_CUSTOMERS = 'commerce-customers' + COMMERCE_DISPUTES = 'commerce-disputes' + COMMERCE_LOCATIONS = 'commerce-locations' + COMMERCE_ORDERS = 'commerce-orders' + COMMERCE_PAYMENT_METHODS = 'commerce-paymentMethods' + COMMERCE_PAYMENTS = 'commerce-payments' + COMMERCE_PRODUCT_CATEGORIES = 'commerce-productCategories' + COMMERCE_PRODUCTS = 'commerce-products' + COMMERCE_TAX_COMPONENTS = 'commerce-taxComponents' + COMMERCE_TRANSACTIONS = 'commerce-transactions' diff --git a/platform/src/codat_platform/models/dataset_status.py b/platform/src/codat_platform/models/dataset_status.py new file mode 100644 index 000000000..2b657c709 --- /dev/null +++ b/platform/src/codat_platform/models/dataset_status.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from enum import Enum + + +class DatasetStatus(str, Enum): + """DatasetStatus enum (lifted from inline OAS enum).""" + INITIAL = 'Initial' + QUEUED = 'Queued' + FETCHING = 'Fetching' + MAP_QUEUED = 'MapQueued' + MAPPING = 'Mapping' + COMPLETE = 'Complete' + FETCH_ERROR = 'FetchError' + MAP_ERROR = 'MapError' + INTERNAL_ERROR = 'InternalError' + PROCESSING_QUEUED = 'ProcessingQueued' + PROCESSING = 'Processing' + PROCESSING_ERROR = 'ProcessingError' + VALIDATION_QUEUED = 'ValidationQueued' + VALIDATING = 'Validating' + VALIDATION_ERROR = 'ValidationError' + AUTH_ERROR = 'AuthError' + CANCELLED = 'Cancelled' + NOT_SUPPORTED = 'NotSupported' + RATE_LIMIT_ERROR = 'RateLimitError' + PERMISSIONS_ERROR = 'PermissionsError' + PREREQUISITE_NOT_MET = 'PrerequisiteNotMet' diff --git a/platform/src/codat_platform/models/error_status.py b/platform/src/codat_platform/models/error_status.py new file mode 100644 index 000000000..ecf0a01b7 --- /dev/null +++ b/platform/src/codat_platform/models/error_status.py @@ -0,0 +1,9 @@ +from __future__ import annotations + +from enum import Enum + + +class ErrorStatus(str, Enum): + """ErrorStatus enum (lifted from inline OAS enum).""" + ACTIVE = 'Active' + RESOLVED = 'Resolved' diff --git a/platform/src/codat_platform/models/errors/__init__.py b/platform/src/codat_platform/models/errors/__init__.py index 852987537..ca0b27caf 100644 --- a/platform/src/codat_platform/models/errors/__init__.py +++ b/platform/src/codat_platform/models/errors/__init__.py @@ -1,39 +1,16 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.errors — Speakeasy-shape exception hierarchy.""" from .codatplatformerror import CodatPlatformError -from typing import Any, TYPE_CHECKING - -from codat_platform.utils.dynamic_imports import lazy_getattr, lazy_dir - -if TYPE_CHECKING: - from .errormessage import ErrorMessage, ErrorMessageData - from .no_response_error import NoResponseError - from .responsevalidationerror import ResponseValidationError - from .sdkerror import SDKError +from .sdkerror import SDKError +from .errormessage import ErrorMessage, ErrorMessageData +from .no_response_error import NoResponseError +from .responsevalidationerror import ResponseValidationError __all__ = [ "CodatPlatformError", + "SDKError", "ErrorMessage", "ErrorMessageData", "NoResponseError", "ResponseValidationError", - "SDKError", ] - -_dynamic_imports: dict[str, str] = { - "ErrorMessage": ".errormessage", - "ErrorMessageData": ".errormessage", - "NoResponseError": ".no_response_error", - "ResponseValidationError": ".responsevalidationerror", - "SDKError": ".sdkerror", -} - - -def __getattr__(attr_name: str) -> Any: - return lazy_getattr( - attr_name, package=__package__, dynamic_imports=_dynamic_imports - ) - - -def __dir__(): - return lazy_dir(dynamic_imports=_dynamic_imports) diff --git a/platform/src/codat_platform/models/errors/codatplatformerror.py b/platform/src/codat_platform/models/errors/codatplatformerror.py index ad2a5ee21..8a9f8510c 100644 --- a/platform/src/codat_platform/models/errors/codatplatformerror.py +++ b/platform/src/codat_platform/models/errors/codatplatformerror.py @@ -1,30 +1,72 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Base error class for codat_platform. -import httpx -from typing import Optional +Generated by pipeline/postprocess_generated.py — do not edit by hand. +""" + +from __future__ import annotations + +from collections.abc import Mapping as _AbcMapping from dataclasses import dataclass, field +from typing import Any, Iterator, Mapping, Optional + + +class CaseInsensitiveHeaders(_AbcMapping): + """Read-only header mapping with case-insensitive lookup, matching the + httpx.Headers a Speakeasy consumer reads. urllib3 hands the POC original-case + keys, so `err.headers["content-type"]` would miss a `Content-Type` header on a + plain dict; here keys are stored lower-cased and lookups are lower-cased too, so + exact-, lower- and mixed-case lookups all match and iteration yields lower-case + keys, exactly as httpx.Headers does.""" + + def __init__(self, data: Optional[Mapping[str, str]] = None) -> None: + self._store = {str(k).lower(): v for k, v in dict(data or {}).items()} + + def __getitem__(self, key: str) -> str: + return self._store[str(key).lower()] + + def __iter__(self) -> Iterator[str]: + return iter(self._store) + + def __len__(self) -> int: + return len(self._store) + + def __repr__(self) -> str: + return f"CaseInsensitiveHeaders({self._store!r})" @dataclass(unsafe_hash=True) class CodatPlatformError(Exception): - """The base class for all HTTP error responses.""" + """The base class for all SDK errors.""" message: str - status_code: int - body: str - headers: httpx.Headers = field(hash=False) - raw_response: httpx.Response = field(hash=False) + status_code: int = 0 + body: str = "" + headers: Mapping[str, str] = field(default_factory=dict, hash=False) + raw_response: Optional[Any] = field(default=None, hash=False) def __init__( - self, message: str, raw_response: httpx.Response, body: Optional[str] = None - ): + self, + message: str, + raw_response: Optional[Any] = None, + body: Optional[str] = None, + status_code: Optional[int] = None, + headers: Optional[Mapping[str, str]] = None, + ) -> None: + # `raw_response` is the 2nd positional arg to match Speakeasy + # (`CodatPlatformError(message, raw_response, body)`). status_code / body / + # headers are derived from raw_response when not passed explicitly. + if status_code is None: + status_code = getattr(raw_response, "status_code", None) or getattr(raw_response, "status", None) or 0 + if body is None: + body = (getattr(raw_response, "text", "") if raw_response is not None else "") or "" + if headers is None: + headers = getattr(raw_response, "headers", None) object.__setattr__(self, "message", message) - object.__setattr__(self, "status_code", raw_response.status_code) - object.__setattr__( - self, "body", body if body is not None else raw_response.text - ) - object.__setattr__(self, "headers", raw_response.headers) + object.__setattr__(self, "status_code", status_code) + object.__setattr__(self, "body", body or "") + object.__setattr__(self, "headers", CaseInsensitiveHeaders(headers)) object.__setattr__(self, "raw_response", raw_response) + super().__init__(message) - def __str__(self): + def __str__(self) -> str: return self.message diff --git a/platform/src/codat_platform/models/errors/errormessage.py b/platform/src/codat_platform/models/errors/errormessage.py index bbadc22a2..8d5deddb4 100644 --- a/platform/src/codat_platform/models/errors/errormessage.py +++ b/platform/src/codat_platform/models/errors/errormessage.py @@ -1,51 +1,41 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""ErrorMessage — typed exception raised for structured Codat API errors. + +Raised when an HTTP response body parses against the ErrorMessage schema +(i.e. Codat-shaped error envelopes with correlationId, statusCode, etc.). +""" from __future__ import annotations -from codat_platform.models.errors import CodatPlatformError -from codat_platform.models.shared import errorvalidation as shared_errorvalidation -from codat_platform.types import BaseModel, OptionalNullable, UNSET -from dataclasses import dataclass, field -import httpx -import pydantic -from typing import Optional -from typing_extensions import Annotated - - -class ErrorMessageData(BaseModel): - can_be_retried: Annotated[Optional[str], pydantic.Field(alias="canBeRetried")] = ( - None - ) - r"""`True` if the error occurred transiently and can be retried.""" - correlation_id: Annotated[Optional[str], pydantic.Field(alias="correlationId")] = ( - None - ) - r"""Unique identifier used to propagate to all downstream services and determine the source of the error.""" - detailed_error_code: Annotated[ - Optional[int], pydantic.Field(alias="detailedErrorCode") - ] = None - r"""Machine readable error code used to automate processes based on the code returned.""" - error: Optional[str] = None - r"""A brief description of the error.""" - service: Optional[str] = None - r"""Codat's service the returned the error.""" - status_code: Annotated[Optional[int], pydantic.Field(alias="statusCode")] = None - r"""The HTTP status code returned by the error.""" - validation: OptionalNullable[shared_errorvalidation.ErrorValidation] = UNSET - r"""A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here.""" - - -@dataclass(unsafe_hash=True) + +from typing import Any, Mapping, Optional + +from .codatplatformerror import CodatPlatformError +from codat_platform.models.shared.errormessage import ErrorMessage as ErrorMessageData + + class ErrorMessage(CodatPlatformError): - r"""Your API request was not properly authorized.""" + """Typed Codat API error response. Access structured fields via `.data`.""" - data: ErrorMessageData = field(hash=False) + data: ErrorMessageData def __init__( self, data: ErrorMessageData, - raw_response: httpx.Response, + raw_response: Optional[Any] = None, body: Optional[str] = None, - ): - message = body or raw_response.text - super().__init__(message, raw_response, body) - object.__setattr__(self, "data", data) + status_code: Optional[int] = None, + headers: Optional[Mapping[str, str]] = None, + ) -> None: + # `raw_response` is the 2nd positional arg to match Speakeasy + # (`ErrorMessage(data, raw_response, body)`). + message = body or str(data) + super().__init__( + message, + raw_response=raw_response, + body=body, + status_code=status_code, + headers=headers, + ) + self.data = data + + +__all__ = ["ErrorMessage", "ErrorMessageData"] diff --git a/platform/src/codat_platform/models/errors/no_response_error.py b/platform/src/codat_platform/models/errors/no_response_error.py index 1deab64bc..acea02af8 100644 --- a/platform/src/codat_platform/models/errors/no_response_error.py +++ b/platform/src/codat_platform/models/errors/no_response_error.py @@ -1,4 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""NoResponseError — raised when the HTTP client never receives a response (timeout, dropped connection, DNS failure).""" + +from __future__ import annotations from dataclasses import dataclass @@ -9,9 +11,12 @@ class NoResponseError(Exception): message: str - def __init__(self, message: str = "No response received"): + def __init__(self, message: str = "No response received") -> None: object.__setattr__(self, "message", message) super().__init__(message) - def __str__(self): + def __str__(self) -> str: return self.message + + +__all__ = ["NoResponseError"] diff --git a/platform/src/codat_platform/models/errors/responsevalidationerror.py b/platform/src/codat_platform/models/errors/responsevalidationerror.py index ef1e5ff6c..06653d235 100644 --- a/platform/src/codat_platform/models/errors/responsevalidationerror.py +++ b/platform/src/codat_platform/models/errors/responsevalidationerror.py @@ -1,27 +1,42 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""ResponseValidationError — raised when a successful HTTP response body cannot be parsed against the expected response model.""" -import httpx -from typing import Optional -from dataclasses import dataclass +from __future__ import annotations -from codat_platform.models.errors import CodatPlatformError +from typing import Any, Mapping, Optional + +from .codatplatformerror import CodatPlatformError -@dataclass(unsafe_hash=True) class ResponseValidationError(CodatPlatformError): - """Error raised when there is a type mismatch between the response data and the expected Pydantic model.""" + """Raised on a pydantic ValidationError when deserialising a Codat response body.""" def __init__( self, message: str, - raw_response: httpx.Response, - cause: Exception, - body: Optional[str] = None, - ): - message = f"{message}: {cause}" - super().__init__(message, raw_response, body) + raw_response: Optional[Any] = None, + cause: Optional[Exception] = None, + body: str = "", + status_code: Optional[int] = None, + headers: Optional[Mapping[str, str]] = None, + ) -> None: + # `raw_response` is the 2nd positional arg, `cause` the 3rd, to match + # Speakeasy (`ResponseValidationError(message, raw_response, cause, body)`). + full_message = f"{message}: {cause}" + super().__init__( + full_message, + raw_response=raw_response, + body=body, + status_code=status_code, + headers=headers, + ) + # Surface the underlying pydantic ValidationError via the standard `__cause__` mechanism + # so callers can do `except errors.ResponseValidationError as e: print(e.cause)`. + self.__cause__ = cause @property - def cause(self): - """Normally the Pydantic ValidationError""" + def cause(self) -> Optional[BaseException]: + """Normally the underlying pydantic ValidationError.""" return self.__cause__ + + +__all__ = ["ResponseValidationError"] diff --git a/platform/src/codat_platform/models/errors/sdkerror.py b/platform/src/codat_platform/models/errors/sdkerror.py index 609bfbb1d..6004739a2 100644 --- a/platform/src/codat_platform/models/errors/sdkerror.py +++ b/platform/src/codat_platform/models/errors/sdkerror.py @@ -1,40 +1,39 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""SDKError — fallback exception for any HTTP error.""" -import httpx -from typing import Optional -from dataclasses import dataclass +from __future__ import annotations + +from typing import Any, Mapping, Optional + +from .codatplatformerror import CodatPlatformError -from codat_platform.models.errors import CodatPlatformError MAX_MESSAGE_LEN = 10_000 -@dataclass(unsafe_hash=True) class SDKError(CodatPlatformError): """The fallback error class if no more specific error class is matched.""" def __init__( - self, message: str, raw_response: httpx.Response, body: Optional[str] = None - ): - body_display = body or raw_response.text or '""' - + self, + message: str, + raw_response: Optional[Any] = None, + body: Optional[str] = None, + status_code: Optional[int] = None, + headers: Optional[Mapping[str, str]] = None, + ) -> None: + # `raw_response` is the 2nd positional arg to match Speakeasy + # (`SDKError(message, raw_response, body)`); existing consumer code that + # re-raises via `SDKError(msg, response)` then stores the response in + # `raw_response`, not `status_code`. status_code / body are derived from + # raw_response when not passed explicitly. + if status_code is None: + status_code = getattr(raw_response, "status_code", None) or getattr(raw_response, "status", None) or 0 + body_display = body or (getattr(raw_response, "text", "") if raw_response is not None else "") or "" if message: message += ": " - message += f"Status {raw_response.status_code}" - - headers = raw_response.headers - content_type = headers.get("content-type", '""') - if content_type != "application/json": - if " " in content_type: - content_type = f'"{content_type}"' - message += f" Content-Type {content_type}" - - if len(body_display) > MAX_MESSAGE_LEN: - truncated = body_display[:MAX_MESSAGE_LEN] - remaining = len(body_display) - MAX_MESSAGE_LEN - body_display = f"{truncated}...and {remaining} more chars" - - message += f". Body: {body_display}" - message = message.strip() - - super().__init__(message, raw_response, body) + message += f"Status {status_code}" + if body_display: + if len(body_display) > MAX_MESSAGE_LEN: + body_display = body_display[:MAX_MESSAGE_LEN] + f"...and {len(body_display) - MAX_MESSAGE_LEN} more chars" + message += f". Body: {body_display}" + super().__init__(message.strip(), status_code=status_code, body=body or "", headers=headers, raw_response=raw_response) diff --git a/platform/src/codat_platform/models/issue_links.py b/platform/src/codat_platform/models/issue_links.py new file mode 100644 index 000000000..cf6a1fdff --- /dev/null +++ b/platform/src/codat_platform/models/issue_links.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class IssueLinks(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + IssueLinks + """ # noqa: E501 + logs: Optional[str] = Field(default=None, description="A link to the validation logs, providing details on any errors or warnings encountered.") + portal: Optional[str] = Field(default=None, description="A link to the company's past data read history in the Codat portal.") + read_more: Optional[str] = Field(default=None, description="A link to Codat's documentation with additional information on how to troubleshoot this issue.", alias="readMore") + __properties: ClassVar[List[str]] = ["logs", "portal", "readMore"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IssueLinks from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IssueLinks from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "logs": obj.get("logs"), + "portal": obj.get("portal"), + "readMore": obj.get("readMore") + }) + return _obj + + + + + +class IssueLinksTypedDict(TypedDict): + """TypedDict variant of IssueLinks, for dict-literal request/response inputs.""" + logs: NotRequired[Optional[str]] + portal: NotRequired[Optional[str]] + read_more: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/modified_date.py b/platform/src/codat_platform/models/modified_date.py new file mode 100644 index 000000000..001b9e664 --- /dev/null +++ b/platform/src/codat_platform/models/modified_date.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class ModifiedDate(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + ModifiedDate + """ # noqa: E501 + modified_date: Optional[str] = Field(default=None, description="The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="modifiedDate") + __properties: ClassVar[List[str]] = ["modifiedDate"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ModifiedDate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ModifiedDate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "modifiedDate": obj.get("modifiedDate") + }) + return _obj + + + + + +class ModifiedDateTypedDict(TypedDict): + """TypedDict variant of ModifiedDate, for dict-literal request/response inputs.""" + modified_date: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/operations/__init__.py b/platform/src/codat_platform/models/operations/__init__.py index 93b2da71f..5fa9cea3b 100644 --- a/platform/src/codat_platform/models/operations/__init__.py +++ b/platform/src/codat_platform/models/operations/__init__.py @@ -1,329 +1,134 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations — re-exports of per-operation request envelopes.""" -from typing import Any, TYPE_CHECKING +from codat_platform.api.companies import ( + AddProductRequest, + AddProductRequestTypedDict, + CreateCompanyRequest, + CreateCompanyRequestTypedDict, + DeleteCompanyRequest, + DeleteCompanyRequestTypedDict, + GetCompanyAccessTokenRequest, + GetCompanyAccessTokenRequestTypedDict, + GetCompanyRequest, + GetCompanyRequestTypedDict, + GetCompanySyncSettingsRequest, + GetCompanySyncSettingsRequestTypedDict, + ListCompaniesRequest, + ListCompaniesRequestTypedDict, + RefreshProductDataRequest, + RefreshProductDataRequestTypedDict, + RemoveProductRequest, + RemoveProductRequestTypedDict, + ReplaceCompanyRequest, + ReplaceCompanyRequestTypedDict, + SetCompanySyncSettingsRequest, + SetCompanySyncSettingsRequestTypedDict, + UpdateCompanyRequest, + UpdateCompanyRequestTypedDict, +) +from codat_platform.api.connection_management import ( + GetConnectionManagementAccessTokenRequest, + GetConnectionManagementAccessTokenRequestTypedDict, +) +from codat_platform.api.connections import ( + CreateConnectionRequest, + CreateConnectionRequestTypedDict, + DeleteConnectionRequest, + DeleteConnectionRequestTypedDict, + GetConnectionRequest, + GetConnectionRequestTypedDict, + ListConnectionsRequest, + ListConnectionsRequestTypedDict, + UnlinkConnectionRequest, + UnlinkConnectionRequestTypedDict, + UpdateConnectionAuthorizationRequest, + UpdateConnectionAuthorizationRequestTypedDict, +) +from codat_platform.api.cors import ( + SetConnectionManagementCorsSettingsRequest, + SetConnectionManagementCorsSettingsRequestTypedDict, +) +from codat_platform.api.custom_data_type import ( + ConfigureCustomDataTypeRequest, + ConfigureCustomDataTypeRequestTypedDict, + GetCustomDataTypeConfigurationRequest, + GetCustomDataTypeConfigurationRequestTypedDict, + ListCustomDataTypeRecordsRequest, + ListCustomDataTypeRecordsRequestTypedDict, + RefreshCustomDataTypeRequest, + RefreshCustomDataTypeRequestTypedDict, +) +from codat_platform.api.integrations import ( + GetIntegrationRequest, + GetIntegrationRequestTypedDict, + GetIntegrationsBrandingRequest, + GetIntegrationsBrandingRequestTypedDict, + ListIntegrationsRequest, + ListIntegrationsRequestTypedDict, +) +from codat_platform.api.push_data import ( + GetCompanyPushHistoryRequest, + GetCompanyPushHistoryRequestTypedDict, + GetCreateUpdateModelOptionsByDataTypeRequest, + GetCreateUpdateModelOptionsByDataTypeRequestTypedDict, + GetPushOperationRequest, + GetPushOperationRequestTypedDict, +) +from codat_platform.api.read_data import ( + GetReadValidationResultsRequest, + GetReadValidationResultsRequestTypedDict, +) +from codat_platform.api.refresh_data import ( + GetCompanyDataStatusRequest, + GetCompanyDataStatusRequestTypedDict, + GetPullOperationRequest, + GetPullOperationRequestTypedDict, + ListPullOperationsRequest, + ListPullOperationsRequestTypedDict, + RefreshCompanyDataRequest, + RefreshCompanyDataRequestTypedDict, + RefreshDataTypeRequest, + RefreshDataTypeRequestTypedDict, +) +from codat_platform.api.settings import ( + CreateAPIKeyRequest, + CreateApiKeyRequest, + CreateApiKeyRequestTypedDict, + DeleteAPIKeyRequest, + DeleteAPIKeyRequest as DeleteApiKeyRequest, + DeleteAPIKeyRequestTypedDict, + DeleteAPIKeyRequestTypedDict as DeleteApiKeyRequestTypedDict, + SetCorsSettingsRequest, + SetCorsSettingsRequestTypedDict, + UpdateProfileRequest, + UpdateProfileRequestTypedDict, + UpdateProfileSyncSettingsRequest, + UpdateProfileSyncSettingsRequestTypedDict, +) +from codat_platform.api.supplemental_data import ( + ConfigureSupplementalDataRequest, + ConfigureSupplementalDataRequestTypedDict, + GetSupplementalDataConfigurationRequest, + GetSupplementalDataConfigurationRequestTypedDict, +) +from codat_platform.api.webhooks import ( + CreateWebhookConsumerRequest, + CreateWebhookConsumerRequestTypedDict, + DeleteWebhookConsumerRequest, + DeleteWebhookConsumerRequestTypedDict, +) -from codat_platform.utils.dynamic_imports import lazy_getattr, lazy_dir +# Speakeasy request-body class names (aliases to POC body classes). +from codat_platform.models.create_connection_request import CreateConnectionRequest as CreateConnectionRequestBody +from codat_platform.models.refresh_product_data_request import RefreshProductDataRequest as RefreshProductDataRequestBody +from codat_platform.models.set_company_sync_settings_request import SetCompanySyncSettingsRequest as SetCompanySyncSettingsRequestBody -if TYPE_CHECKING: - from .add_product import AddProductRequest, AddProductRequestTypedDict - from .configure_custom_data_type import ( - ConfigureCustomDataTypeRequest, - ConfigureCustomDataTypeRequestTypedDict, - ) - from .configure_supplemental_data import ( - ConfigureSupplementalDataRequest, - ConfigureSupplementalDataRequestTypedDict, - DataType, - ) - from .create_connection import ( - CreateConnectionRequest, - CreateConnectionRequestBody, - CreateConnectionRequestBodyTypedDict, - CreateConnectionRequestTypedDict, - ) - from .delete_api_key import DeleteAPIKeyRequest, DeleteAPIKeyRequestTypedDict - from .delete_company import DeleteCompanyRequest, DeleteCompanyRequestTypedDict - from .delete_connection import ( - DeleteConnectionRequest, - DeleteConnectionRequestTypedDict, - ) - from .delete_webhook_consumer import ( - DeleteWebhookConsumerRequest, - DeleteWebhookConsumerRequestTypedDict, - ) - from .get_company import GetCompanyRequest, GetCompanyRequestTypedDict - from .get_company_access_token import ( - GetCompanyAccessTokenRequest, - GetCompanyAccessTokenRequestTypedDict, - ) - from .get_company_data_status import ( - GetCompanyDataStatusRequest, - GetCompanyDataStatusRequestTypedDict, - ) - from .get_company_push_history import ( - GetCompanyPushHistoryRequest, - GetCompanyPushHistoryRequestTypedDict, - ) - from .get_company_syncsettings import ( - GetCompanySyncSettingsRequest, - GetCompanySyncSettingsRequestTypedDict, - ) - from .get_connection import GetConnectionRequest, GetConnectionRequestTypedDict - from .get_connection_management_access_token import ( - GetConnectionManagementAccessTokenRequest, - GetConnectionManagementAccessTokenRequestTypedDict, - ) - from .get_create_update_model_options_by_data_type import ( - GetCreateUpdateModelOptionsByDataTypeRequest, - GetCreateUpdateModelOptionsByDataTypeRequestTypedDict, - ) - from .get_custom_data_type_configuration import ( - GetCustomDataTypeConfigurationRequest, - GetCustomDataTypeConfigurationRequestTypedDict, - ) - from .get_integration import GetIntegrationRequest, GetIntegrationRequestTypedDict - from .get_integrations_branding import ( - GetIntegrationsBrandingRequest, - GetIntegrationsBrandingRequestTypedDict, - ) - from .get_pull_operation import ( - GetPullOperationRequest, - GetPullOperationRequestTypedDict, - ) - from .get_push_operation import ( - GetPushOperationRequest, - GetPushOperationRequestTypedDict, - ) - from .get_read_validation_results import ( - GetReadValidationResultsRequest, - GetReadValidationResultsRequestTypedDict, - ) - from .get_supplemental_data_configuration import ( - GetSupplementalDataConfigurationRequest, - GetSupplementalDataConfigurationRequestTypedDict, - PathParamDataType, - ) - from .list_companies import ListCompaniesRequest, ListCompaniesRequestTypedDict - from .list_connections import ( - ListConnectionsRequest, - ListConnectionsRequestTypedDict, - ) - from .list_custom_data_type_records import ( - ListCustomDataTypeRecordsRequest, - ListCustomDataTypeRecordsRequestTypedDict, - ) - from .list_integrations import ( - ListIntegrationsRequest, - ListIntegrationsRequestTypedDict, - ) - from .list_pull_operations import ( - ListPullOperationsRequest, - ListPullOperationsRequestTypedDict, - ) - from .refresh_company_data import ( - RefreshCompanyDataRequest, - RefreshCompanyDataRequestTypedDict, - ) - from .refresh_custom_data_type import ( - RefreshCustomDataTypeRequest, - RefreshCustomDataTypeRequestTypedDict, - ) - from .refresh_data_type import ( - RefreshDataTypeRequest, - RefreshDataTypeRequestTypedDict, - ) - from .refresh_product_data import ( - RefreshProductDataRequest, - RefreshProductDataRequestBody, - RefreshProductDataRequestBodyTypedDict, - RefreshProductDataRequestTypedDict, - ) - from .remove_product import RemoveProductRequest, RemoveProductRequestTypedDict - from .replace_company import ReplaceCompanyRequest, ReplaceCompanyRequestTypedDict - from .set_company_syncsettings import ( - SetCompanySyncSettingsRequest, - SetCompanySyncSettingsRequestBody, - SetCompanySyncSettingsRequestBodyTypedDict, - SetCompanySyncSettingsRequestTypedDict, - ) - from .unlink_connection import ( - UnlinkConnectionRequest, - UnlinkConnectionRequestTypedDict, - ) - from .update_company import UpdateCompanyRequest, UpdateCompanyRequestTypedDict - from .update_connection_authorization import ( - UpdateConnectionAuthorizationRequest, - UpdateConnectionAuthorizationRequestTypedDict, - ) - from .update_profile_syncsettings import ( - UpdateProfileSyncSettingsRequestBody, - UpdateProfileSyncSettingsRequestBodyTypedDict, - ) +# Speakeasy operations names POC defines elsewhere (response bodies, op-param enums). +from codat_platform.models.operations.get_supplemental_data_configuration import PathParamDataType +from codat_platform.models.update_profile_sync_settings_request import UpdateProfileSyncSettingsRequestBody +from codat_platform.api.settings import UpdateProfileSyncSettingsRequestBodyTypedDict -__all__ = [ - "AddProductRequest", - "AddProductRequestTypedDict", - "ConfigureCustomDataTypeRequest", - "ConfigureCustomDataTypeRequestTypedDict", - "ConfigureSupplementalDataRequest", - "ConfigureSupplementalDataRequestTypedDict", - "CreateConnectionRequest", - "CreateConnectionRequestBody", - "CreateConnectionRequestBodyTypedDict", - "CreateConnectionRequestTypedDict", - "DataType", - "DeleteAPIKeyRequest", - "DeleteAPIKeyRequestTypedDict", - "DeleteCompanyRequest", - "DeleteCompanyRequestTypedDict", - "DeleteConnectionRequest", - "DeleteConnectionRequestTypedDict", - "DeleteWebhookConsumerRequest", - "DeleteWebhookConsumerRequestTypedDict", - "GetCompanyAccessTokenRequest", - "GetCompanyAccessTokenRequestTypedDict", - "GetCompanyDataStatusRequest", - "GetCompanyDataStatusRequestTypedDict", - "GetCompanyPushHistoryRequest", - "GetCompanyPushHistoryRequestTypedDict", - "GetCompanyRequest", - "GetCompanyRequestTypedDict", - "GetCompanySyncSettingsRequest", - "GetCompanySyncSettingsRequestTypedDict", - "GetConnectionManagementAccessTokenRequest", - "GetConnectionManagementAccessTokenRequestTypedDict", - "GetConnectionRequest", - "GetConnectionRequestTypedDict", - "GetCreateUpdateModelOptionsByDataTypeRequest", - "GetCreateUpdateModelOptionsByDataTypeRequestTypedDict", - "GetCustomDataTypeConfigurationRequest", - "GetCustomDataTypeConfigurationRequestTypedDict", - "GetIntegrationRequest", - "GetIntegrationRequestTypedDict", - "GetIntegrationsBrandingRequest", - "GetIntegrationsBrandingRequestTypedDict", - "GetPullOperationRequest", - "GetPullOperationRequestTypedDict", - "GetPushOperationRequest", - "GetPushOperationRequestTypedDict", - "GetReadValidationResultsRequest", - "GetReadValidationResultsRequestTypedDict", - "GetSupplementalDataConfigurationRequest", - "GetSupplementalDataConfigurationRequestTypedDict", - "ListCompaniesRequest", - "ListCompaniesRequestTypedDict", - "ListConnectionsRequest", - "ListConnectionsRequestTypedDict", - "ListCustomDataTypeRecordsRequest", - "ListCustomDataTypeRecordsRequestTypedDict", - "ListIntegrationsRequest", - "ListIntegrationsRequestTypedDict", - "ListPullOperationsRequest", - "ListPullOperationsRequestTypedDict", - "PathParamDataType", - "RefreshCompanyDataRequest", - "RefreshCompanyDataRequestTypedDict", - "RefreshCustomDataTypeRequest", - "RefreshCustomDataTypeRequestTypedDict", - "RefreshDataTypeRequest", - "RefreshDataTypeRequestTypedDict", - "RefreshProductDataRequest", - "RefreshProductDataRequestBody", - "RefreshProductDataRequestBodyTypedDict", - "RefreshProductDataRequestTypedDict", - "RemoveProductRequest", - "RemoveProductRequestTypedDict", - "ReplaceCompanyRequest", - "ReplaceCompanyRequestTypedDict", - "SetCompanySyncSettingsRequest", - "SetCompanySyncSettingsRequestBody", - "SetCompanySyncSettingsRequestBodyTypedDict", - "SetCompanySyncSettingsRequestTypedDict", - "UnlinkConnectionRequest", - "UnlinkConnectionRequestTypedDict", - "UpdateCompanyRequest", - "UpdateCompanyRequestTypedDict", - "UpdateConnectionAuthorizationRequest", - "UpdateConnectionAuthorizationRequestTypedDict", - "UpdateProfileSyncSettingsRequestBody", - "UpdateProfileSyncSettingsRequestBodyTypedDict", -] - -_dynamic_imports: dict[str, str] = { - "AddProductRequest": ".add_product", - "AddProductRequestTypedDict": ".add_product", - "ConfigureCustomDataTypeRequest": ".configure_custom_data_type", - "ConfigureCustomDataTypeRequestTypedDict": ".configure_custom_data_type", - "ConfigureSupplementalDataRequest": ".configure_supplemental_data", - "ConfigureSupplementalDataRequestTypedDict": ".configure_supplemental_data", - "DataType": ".configure_supplemental_data", - "CreateConnectionRequest": ".create_connection", - "CreateConnectionRequestBody": ".create_connection", - "CreateConnectionRequestBodyTypedDict": ".create_connection", - "CreateConnectionRequestTypedDict": ".create_connection", - "DeleteAPIKeyRequest": ".delete_api_key", - "DeleteAPIKeyRequestTypedDict": ".delete_api_key", - "DeleteCompanyRequest": ".delete_company", - "DeleteCompanyRequestTypedDict": ".delete_company", - "DeleteConnectionRequest": ".delete_connection", - "DeleteConnectionRequestTypedDict": ".delete_connection", - "DeleteWebhookConsumerRequest": ".delete_webhook_consumer", - "DeleteWebhookConsumerRequestTypedDict": ".delete_webhook_consumer", - "GetCompanyRequest": ".get_company", - "GetCompanyRequestTypedDict": ".get_company", - "GetCompanyAccessTokenRequest": ".get_company_access_token", - "GetCompanyAccessTokenRequestTypedDict": ".get_company_access_token", - "GetCompanyDataStatusRequest": ".get_company_data_status", - "GetCompanyDataStatusRequestTypedDict": ".get_company_data_status", - "GetCompanyPushHistoryRequest": ".get_company_push_history", - "GetCompanyPushHistoryRequestTypedDict": ".get_company_push_history", - "GetCompanySyncSettingsRequest": ".get_company_syncsettings", - "GetCompanySyncSettingsRequestTypedDict": ".get_company_syncsettings", - "GetConnectionRequest": ".get_connection", - "GetConnectionRequestTypedDict": ".get_connection", - "GetConnectionManagementAccessTokenRequest": ".get_connection_management_access_token", - "GetConnectionManagementAccessTokenRequestTypedDict": ".get_connection_management_access_token", - "GetCreateUpdateModelOptionsByDataTypeRequest": ".get_create_update_model_options_by_data_type", - "GetCreateUpdateModelOptionsByDataTypeRequestTypedDict": ".get_create_update_model_options_by_data_type", - "GetCustomDataTypeConfigurationRequest": ".get_custom_data_type_configuration", - "GetCustomDataTypeConfigurationRequestTypedDict": ".get_custom_data_type_configuration", - "GetIntegrationRequest": ".get_integration", - "GetIntegrationRequestTypedDict": ".get_integration", - "GetIntegrationsBrandingRequest": ".get_integrations_branding", - "GetIntegrationsBrandingRequestTypedDict": ".get_integrations_branding", - "GetPullOperationRequest": ".get_pull_operation", - "GetPullOperationRequestTypedDict": ".get_pull_operation", - "GetPushOperationRequest": ".get_push_operation", - "GetPushOperationRequestTypedDict": ".get_push_operation", - "GetReadValidationResultsRequest": ".get_read_validation_results", - "GetReadValidationResultsRequestTypedDict": ".get_read_validation_results", - "GetSupplementalDataConfigurationRequest": ".get_supplemental_data_configuration", - "GetSupplementalDataConfigurationRequestTypedDict": ".get_supplemental_data_configuration", - "PathParamDataType": ".get_supplemental_data_configuration", - "ListCompaniesRequest": ".list_companies", - "ListCompaniesRequestTypedDict": ".list_companies", - "ListConnectionsRequest": ".list_connections", - "ListConnectionsRequestTypedDict": ".list_connections", - "ListCustomDataTypeRecordsRequest": ".list_custom_data_type_records", - "ListCustomDataTypeRecordsRequestTypedDict": ".list_custom_data_type_records", - "ListIntegrationsRequest": ".list_integrations", - "ListIntegrationsRequestTypedDict": ".list_integrations", - "ListPullOperationsRequest": ".list_pull_operations", - "ListPullOperationsRequestTypedDict": ".list_pull_operations", - "RefreshCompanyDataRequest": ".refresh_company_data", - "RefreshCompanyDataRequestTypedDict": ".refresh_company_data", - "RefreshCustomDataTypeRequest": ".refresh_custom_data_type", - "RefreshCustomDataTypeRequestTypedDict": ".refresh_custom_data_type", - "RefreshDataTypeRequest": ".refresh_data_type", - "RefreshDataTypeRequestTypedDict": ".refresh_data_type", - "RefreshProductDataRequest": ".refresh_product_data", - "RefreshProductDataRequestBody": ".refresh_product_data", - "RefreshProductDataRequestBodyTypedDict": ".refresh_product_data", - "RefreshProductDataRequestTypedDict": ".refresh_product_data", - "RemoveProductRequest": ".remove_product", - "RemoveProductRequestTypedDict": ".remove_product", - "ReplaceCompanyRequest": ".replace_company", - "ReplaceCompanyRequestTypedDict": ".replace_company", - "SetCompanySyncSettingsRequest": ".set_company_syncsettings", - "SetCompanySyncSettingsRequestBody": ".set_company_syncsettings", - "SetCompanySyncSettingsRequestBodyTypedDict": ".set_company_syncsettings", - "SetCompanySyncSettingsRequestTypedDict": ".set_company_syncsettings", - "UnlinkConnectionRequest": ".unlink_connection", - "UnlinkConnectionRequestTypedDict": ".unlink_connection", - "UpdateCompanyRequest": ".update_company", - "UpdateCompanyRequestTypedDict": ".update_company", - "UpdateConnectionAuthorizationRequest": ".update_connection_authorization", - "UpdateConnectionAuthorizationRequestTypedDict": ".update_connection_authorization", - "UpdateProfileSyncSettingsRequestBody": ".update_profile_syncsettings", - "UpdateProfileSyncSettingsRequestBodyTypedDict": ".update_profile_syncsettings", -} - - -def __getattr__(attr_name: str) -> Any: - return lazy_getattr( - attr_name, package=__package__, dynamic_imports=_dynamic_imports - ) - - -def __dir__(): - return lazy_dir(dynamic_imports=_dynamic_imports) +# Speakeasy TypedDict companions for aliased names. +from codat_platform.models.create_connection_request import CreateConnectionRequestTypedDict as CreateConnectionRequestBodyTypedDict +from codat_platform.models.refresh_product_data_request import RefreshProductDataRequestTypedDict as RefreshProductDataRequestBodyTypedDict +from codat_platform.models.set_company_sync_settings_request import SetCompanySyncSettingsRequestTypedDict as SetCompanySyncSettingsRequestBodyTypedDict diff --git a/platform/src/codat_platform/models/operations/add_product.py b/platform/src/codat_platform/models/operations/add_product.py index 4b2c37d7b..8b99b6619 100644 --- a/platform/src/codat_platform/models/operations/add_product.py +++ b/platform/src/codat_platform/models/operations/add_product.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.add_product — re-export of the add_product operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class AddProductRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - product_identifier: str - r"""Human-readable product identifier for a product.""" - - -class AddProductRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - product_identifier: Annotated[ - str, - pydantic.Field(alias="productIdentifier"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Human-readable product identifier for a product.""" +from codat_platform.api.companies import AddProductRequest +from codat_platform.api.companies import AddProductRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/configure_custom_data_type.py b/platform/src/codat_platform/models/operations/configure_custom_data_type.py index 76aec6814..35a19ad87 100644 --- a/platform/src/codat_platform/models/operations/configure_custom_data_type.py +++ b/platform/src/codat_platform/models/operations/configure_custom_data_type.py @@ -1,61 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.configure_custom_data_type — re-export of the configure_custom_data_type operation envelope.""" -from __future__ import annotations -from codat_platform.models.shared import ( - customdatatypeconfiguration as shared_customdatatypeconfiguration, -) -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, RequestMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ConfigureCustomDataTypeRequestTypedDict(TypedDict): - custom_data_identifier: str - r"""Unique identifier for a custom data type.""" - platform_key: str - r"""A unique 4-letter key to represent a platform in each integration.""" - custom_data_type_configuration: NotRequired[ - shared_customdatatypeconfiguration.CustomDataTypeConfigurationTypedDict - ] - r"""Custom data type configuration for the specified platform.""" - - -class ConfigureCustomDataTypeRequest(BaseModel): - custom_data_identifier: Annotated[ - str, - pydantic.Field(alias="customDataIdentifier"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a custom data type.""" - - platform_key: Annotated[ - str, - pydantic.Field(alias="platformKey"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""A unique 4-letter key to represent a platform in each integration.""" - - custom_data_type_configuration: Annotated[ - Optional[shared_customdatatypeconfiguration.CustomDataTypeConfiguration], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - r"""Custom data type configuration for the specified platform.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["CustomDataTypeConfiguration"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_platform.api.custom_data_type import ConfigureCustomDataTypeRequest +from codat_platform.api.custom_data_type import ConfigureCustomDataTypeRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/configure_supplemental_data.py b/platform/src/codat_platform/models/operations/configure_supplemental_data.py index 9c7c7da1b..2a15c4004 100644 --- a/platform/src/codat_platform/models/operations/configure_supplemental_data.py +++ b/platform/src/codat_platform/models/operations/configure_supplemental_data.py @@ -1,88 +1,28 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - from __future__ import annotations -from codat_platform.models.shared import ( - supplementaldataconfiguration as shared_supplementaldataconfiguration, -) -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, RequestMetadata + from enum import Enum -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict class DataType(str, Enum): - r"""Data types that support supplemental data""" - - CHART_OF_ACCOUNTS = "chartOfAccounts" - BILLS = "bills" - COMPANY = "company" - CREDIT_NOTES = "creditNotes" - CUSTOMERS = "customers" - INVOICES = "invoices" - ITEMS = "items" - JOURNAL_ENTRIES = "journalEntries" - SUPPLIERS = "suppliers" - TAX_RATES = "taxRates" - COMMERCE_COMPANY_INFO = "commerce-companyInfo" - COMMERCE_CUSTOMERS = "commerce-customers" - COMMERCE_DISPUTES = "commerce-disputes" - COMMERCE_LOCATIONS = "commerce-locations" - COMMERCE_ORDERS = "commerce-orders" - COMMERCE_PAYMENTS = "commerce-payments" - COMMERCE_PAYMENT_METHODS = "commerce-paymentMethods" - COMMERCE_PRODUCTS = "commerce-products" - COMMERCE_PRODUCT_CATEGORIES = "commerce-productCategories" - COMMERCE_TAX_COMPONENTS = "commerce-taxComponents" - COMMERCE_TRANSACTIONS = "commerce-transactions" - - -class ConfigureSupplementalDataRequestTypedDict(TypedDict): - data_type: DataType - r"""Supported supplemental data data type.""" - platform_key: str - r"""A unique 4-letter key to represent a platform in each integration.""" - supplemental_data_configuration: NotRequired[ - shared_supplementaldataconfiguration.SupplementalDataConfigurationTypedDict - ] - r"""The configuration for the specified platform and data type.""" - - -class ConfigureSupplementalDataRequest(BaseModel): - data_type: Annotated[ - DataType, - pydantic.Field(alias="dataType"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Supported supplemental data data type.""" - - platform_key: Annotated[ - str, - pydantic.Field(alias="platformKey"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""A unique 4-letter key to represent a platform in each integration.""" - - supplemental_data_configuration: Annotated[ - Optional[shared_supplementaldataconfiguration.SupplementalDataConfiguration], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - r"""The configuration for the specified platform and data type.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["SupplementalDataConfiguration"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m + """Operation-parameter enum (lifted from inline OAS enum on configure-supplemental-data).""" + CHART_OF_ACCOUNTS = 'chartOfAccounts' + BILLS = 'bills' + COMPANY = 'company' + CREDIT_NOTES = 'creditNotes' + CUSTOMERS = 'customers' + INVOICES = 'invoices' + ITEMS = 'items' + JOURNAL_ENTRIES = 'journalEntries' + SUPPLIERS = 'suppliers' + TAX_RATES = 'taxRates' + COMMERCE_COMPANY_INFO = 'commerce-companyInfo' + COMMERCE_CUSTOMERS = 'commerce-customers' + COMMERCE_DISPUTES = 'commerce-disputes' + COMMERCE_LOCATIONS = 'commerce-locations' + COMMERCE_ORDERS = 'commerce-orders' + COMMERCE_PAYMENTS = 'commerce-payments' + COMMERCE_PAYMENT_METHODS = 'commerce-paymentMethods' + COMMERCE_PRODUCTS = 'commerce-products' + COMMERCE_PRODUCT_CATEGORIES = 'commerce-productCategories' + COMMERCE_TAX_COMPONENTS = 'commerce-taxComponents' + COMMERCE_TRANSACTIONS = 'commerce-transactions' diff --git a/platform/src/codat_platform/models/operations/create_connection.py b/platform/src/codat_platform/models/operations/create_connection.py index 07f22aec2..82e60a861 100644 --- a/platform/src/codat_platform/models/operations/create_connection.py +++ b/platform/src/codat_platform/models/operations/create_connection.py @@ -1,77 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.create_connection — re-export of the create_connection operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, RequestMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class CreateConnectionRequestBodyTypedDict(TypedDict): - platform_key: NotRequired[str] - r"""A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys.""" - - -class CreateConnectionRequestBody(BaseModel): - platform_key: Annotated[Optional[str], pydantic.Field(alias="platformKey")] = None - r"""A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["platformKey"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m - - -class CreateConnectionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - request_body: NotRequired[CreateConnectionRequestBodyTypedDict] - - -class CreateConnectionRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - request_body: Annotated[ - Optional[CreateConnectionRequestBody], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["RequestBody"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m - - -try: - CreateConnectionRequestBody.model_rebuild() -except NameError: - pass +from codat_platform.api.connections import CreateConnectionRequest +from codat_platform.models.create_connection_request import CreateConnectionRequest as CreateConnectionRequestBody +from codat_platform.models.create_connection_request import CreateConnectionRequestTypedDict as CreateConnectionRequestBodyTypedDict +from codat_platform.api.connections import CreateConnectionRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/delete_api_key.py b/platform/src/codat_platform/models/operations/delete_api_key.py index fc971472b..713bc3f1d 100644 --- a/platform/src/codat_platform/models/operations/delete_api_key.py +++ b/platform/src/codat_platform/models/operations/delete_api_key.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.delete_api_key — re-export of the delete_api_key operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class DeleteAPIKeyRequestTypedDict(TypedDict): - api_key_id: str - r"""Unique identifier for api key.""" - - -class DeleteAPIKeyRequest(BaseModel): - api_key_id: Annotated[ - str, - pydantic.Field(alias="apiKeyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for api key.""" +from codat_platform.api.settings import DeleteAPIKeyRequest +from codat_platform.api.settings import DeleteAPIKeyRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/delete_company.py b/platform/src/codat_platform/models/operations/delete_company.py index f523d45fe..91cb56cf6 100644 --- a/platform/src/codat_platform/models/operations/delete_company.py +++ b/platform/src/codat_platform/models/operations/delete_company.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.delete_company — re-export of the delete_company operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class DeleteCompanyRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class DeleteCompanyRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" +from codat_platform.api.companies import DeleteCompanyRequest +from codat_platform.api.companies import DeleteCompanyRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/delete_connection.py b/platform/src/codat_platform/models/operations/delete_connection.py index d3b4a8e46..0d43b5990 100644 --- a/platform/src/codat_platform/models/operations/delete_connection.py +++ b/platform/src/codat_platform/models/operations/delete_connection.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.delete_connection — re-export of the delete_connection operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class DeleteConnectionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - - -class DeleteConnectionRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" +from codat_platform.api.connections import DeleteConnectionRequest +from codat_platform.api.connections import DeleteConnectionRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/delete_webhook_consumer.py b/platform/src/codat_platform/models/operations/delete_webhook_consumer.py index c5d6f3ea0..989c1ff4b 100644 --- a/platform/src/codat_platform/models/operations/delete_webhook_consumer.py +++ b/platform/src/codat_platform/models/operations/delete_webhook_consumer.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.delete_webhook_consumer — re-export of the delete_webhook_consumer operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class DeleteWebhookConsumerRequestTypedDict(TypedDict): - webhook_id: str - r"""Unique identifier for the webhook consumer.""" - - -class DeleteWebhookConsumerRequest(BaseModel): - webhook_id: Annotated[ - str, - pydantic.Field(alias="webhookId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for the webhook consumer.""" +from codat_platform.api.webhooks import DeleteWebhookConsumerRequest +from codat_platform.api.webhooks import DeleteWebhookConsumerRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_company.py b/platform/src/codat_platform/models/operations/get_company.py index 7ec274065..33d91757e 100644 --- a/platform/src/codat_platform/models/operations/get_company.py +++ b/platform/src/codat_platform/models/operations/get_company.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_company — re-export of the get_company operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetCompanyRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class GetCompanyRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" +from codat_platform.api.companies import GetCompanyRequest +from codat_platform.api.companies import GetCompanyRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_company_access_token.py b/platform/src/codat_platform/models/operations/get_company_access_token.py index 87b3fde9a..dc31ae7a8 100644 --- a/platform/src/codat_platform/models/operations/get_company_access_token.py +++ b/platform/src/codat_platform/models/operations/get_company_access_token.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_company_access_token — re-export of the get_company_access_token operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetCompanyAccessTokenRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class GetCompanyAccessTokenRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" +from codat_platform.api.companies import GetCompanyAccessTokenRequest +from codat_platform.api.companies import GetCompanyAccessTokenRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_company_data_status.py b/platform/src/codat_platform/models/operations/get_company_data_status.py index 70a004263..e918dfd6f 100644 --- a/platform/src/codat_platform/models/operations/get_company_data_status.py +++ b/platform/src/codat_platform/models/operations/get_company_data_status.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_company_data_status — re-export of the get_company_data_status operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetCompanyDataStatusRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class GetCompanyDataStatusRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" +from codat_platform.api.refresh_data import GetCompanyDataStatusRequest +from codat_platform.api.refresh_data import GetCompanyDataStatusRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_company_push_history.py b/platform/src/codat_platform/models/operations/get_company_push_history.py index b12b2b19c..1525c9c09 100644 --- a/platform/src/codat_platform/models/operations/get_company_push_history.py +++ b/platform/src/codat_platform/models/operations/get_company_push_history.py @@ -1,73 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_company_push_history — re-export of the get_company_push_history operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, QueryParamMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class GetCompanyPushHistoryRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - order_by: NotRequired[str] - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - page: NotRequired[int] - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - page_size: NotRequired[int] - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - query: NotRequired[str] - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - - -class GetCompanyPushHistoryRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - order_by: Annotated[ - Optional[str], - pydantic.Field(alias="orderBy"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - - page: Annotated[ - Optional[int], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 1 - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - - page_size: Annotated[ - Optional[int], - pydantic.Field(alias="pageSize"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 100 - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - - query: Annotated[ - Optional[str], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["orderBy", "page", "pageSize", "query"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_platform.api.push_data import GetCompanyPushHistoryRequest +from codat_platform.api.push_data import GetCompanyPushHistoryRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_company_syncsettings.py b/platform/src/codat_platform/models/operations/get_company_syncsettings.py index 133215ac7..d7a41a8a3 100644 --- a/platform/src/codat_platform/models/operations/get_company_syncsettings.py +++ b/platform/src/codat_platform/models/operations/get_company_syncsettings.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_company_syncsettings — re-export of the get_company_syncsettings operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetCompanySyncSettingsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class GetCompanySyncSettingsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" +from codat_platform.api.companies import GetCompanySyncSettingsRequest +from codat_platform.api.companies import GetCompanySyncSettingsRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_connection.py b/platform/src/codat_platform/models/operations/get_connection.py index 314a92086..52ca3772b 100644 --- a/platform/src/codat_platform/models/operations/get_connection.py +++ b/platform/src/codat_platform/models/operations/get_connection.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_connection — re-export of the get_connection operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetConnectionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - - -class GetConnectionRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" +from codat_platform.api.connections import GetConnectionRequest +from codat_platform.api.connections import GetConnectionRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_connection_management_access_token.py b/platform/src/codat_platform/models/operations/get_connection_management_access_token.py index 01015b32e..c9c2aa7b4 100644 --- a/platform/src/codat_platform/models/operations/get_connection_management_access_token.py +++ b/platform/src/codat_platform/models/operations/get_connection_management_access_token.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_connection_management_access_token — re-export of the get_connection_management_access_token operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetConnectionManagementAccessTokenRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class GetConnectionManagementAccessTokenRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" +from codat_platform.api.connection_management import GetConnectionManagementAccessTokenRequest +from codat_platform.api.connection_management import GetConnectionManagementAccessTokenRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_create_update_model_options_by_data_type.py b/platform/src/codat_platform/models/operations/get_create_update_model_options_by_data_type.py index 71e09dfff..62b5d9d47 100644 --- a/platform/src/codat_platform/models/operations/get_create_update_model_options_by_data_type.py +++ b/platform/src/codat_platform/models/operations/get_create_update_model_options_by_data_type.py @@ -1,40 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_create_update_model_options_by_data_type — re-export of the get_create_update_model_options_by_data_type operation envelope.""" -from __future__ import annotations -from codat_platform.models.shared import schema_datatype as shared_schema_datatype -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetCreateUpdateModelOptionsByDataTypeRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - data_type: shared_schema_datatype.SchemaDataType - r"""The key of a Codat data type.""" - - -class GetCreateUpdateModelOptionsByDataTypeRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - data_type: Annotated[ - shared_schema_datatype.SchemaDataType, - pydantic.Field(alias="dataType"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""The key of a Codat data type.""" +from codat_platform.api.push_data import GetCreateUpdateModelOptionsByDataTypeRequest +from codat_platform.api.push_data import GetCreateUpdateModelOptionsByDataTypeRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_custom_data_type_configuration.py b/platform/src/codat_platform/models/operations/get_custom_data_type_configuration.py index 8f6d69055..103fc515c 100644 --- a/platform/src/codat_platform/models/operations/get_custom_data_type_configuration.py +++ b/platform/src/codat_platform/models/operations/get_custom_data_type_configuration.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_custom_data_type_configuration — re-export of the get_custom_data_type_configuration operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetCustomDataTypeConfigurationRequestTypedDict(TypedDict): - custom_data_identifier: str - r"""Unique identifier for a custom data type.""" - platform_key: str - r"""A unique 4-letter key to represent a platform in each integration.""" - - -class GetCustomDataTypeConfigurationRequest(BaseModel): - custom_data_identifier: Annotated[ - str, - pydantic.Field(alias="customDataIdentifier"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a custom data type.""" - - platform_key: Annotated[ - str, - pydantic.Field(alias="platformKey"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""A unique 4-letter key to represent a platform in each integration.""" +from codat_platform.api.custom_data_type import GetCustomDataTypeConfigurationRequest +from codat_platform.api.custom_data_type import GetCustomDataTypeConfigurationRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_integration.py b/platform/src/codat_platform/models/operations/get_integration.py index de1124bce..daef6a664 100644 --- a/platform/src/codat_platform/models/operations/get_integration.py +++ b/platform/src/codat_platform/models/operations/get_integration.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_integration — re-export of the get_integration operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetIntegrationRequestTypedDict(TypedDict): - platform_key: str - r"""A unique 4-letter key to represent a platform in each integration.""" - - -class GetIntegrationRequest(BaseModel): - platform_key: Annotated[ - str, - pydantic.Field(alias="platformKey"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""A unique 4-letter key to represent a platform in each integration.""" +from codat_platform.api.integrations import GetIntegrationRequest +from codat_platform.api.integrations import GetIntegrationRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_integrations_branding.py b/platform/src/codat_platform/models/operations/get_integrations_branding.py index b67788815..59d53ad5d 100644 --- a/platform/src/codat_platform/models/operations/get_integrations_branding.py +++ b/platform/src/codat_platform/models/operations/get_integrations_branding.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_integrations_branding — re-export of the get_integrations_branding operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetIntegrationsBrandingRequestTypedDict(TypedDict): - platform_key: str - r"""A unique 4-letter key to represent a platform in each integration.""" - - -class GetIntegrationsBrandingRequest(BaseModel): - platform_key: Annotated[ - str, - pydantic.Field(alias="platformKey"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""A unique 4-letter key to represent a platform in each integration.""" +from codat_platform.api.integrations import GetIntegrationsBrandingRequest +from codat_platform.api.integrations import GetIntegrationsBrandingRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_pull_operation.py b/platform/src/codat_platform/models/operations/get_pull_operation.py index ccf9e170b..5af07d6b3 100644 --- a/platform/src/codat_platform/models/operations/get_pull_operation.py +++ b/platform/src/codat_platform/models/operations/get_pull_operation.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_pull_operation — re-export of the get_pull_operation operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetPullOperationRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - dataset_id: str - r"""Unique identifier for the dataset that completed its sync.""" - - -class GetPullOperationRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - dataset_id: Annotated[ - str, - pydantic.Field(alias="datasetId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for the dataset that completed its sync.""" +from codat_platform.api.refresh_data import GetPullOperationRequest +from codat_platform.api.refresh_data import GetPullOperationRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_push_operation.py b/platform/src/codat_platform/models/operations/get_push_operation.py index 2e9c65775..ac081ac0c 100644 --- a/platform/src/codat_platform/models/operations/get_push_operation.py +++ b/platform/src/codat_platform/models/operations/get_push_operation.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_push_operation — re-export of the get_push_operation operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetPushOperationRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - push_operation_key: str - r"""Push operation key.""" - - -class GetPushOperationRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - push_operation_key: Annotated[ - str, - pydantic.Field(alias="pushOperationKey"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Push operation key.""" +from codat_platform.api.push_data import GetPushOperationRequest +from codat_platform.api.push_data import GetPushOperationRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_read_validation_results.py b/platform/src/codat_platform/models/operations/get_read_validation_results.py index 75f5aa0c8..1ed76b7bd 100644 --- a/platform/src/codat_platform/models/operations/get_read_validation_results.py +++ b/platform/src/codat_platform/models/operations/get_read_validation_results.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.get_read_validation_results — re-export of the get_read_validation_results operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetReadValidationResultsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - dataset_id: str - r"""Unique identifier for the dataset that completed its sync.""" - - -class GetReadValidationResultsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - dataset_id: Annotated[ - str, - pydantic.Field(alias="datasetId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for the dataset that completed its sync.""" +from codat_platform.api.read_data import GetReadValidationResultsRequest +from codat_platform.api.read_data import GetReadValidationResultsRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/get_supplemental_data_configuration.py b/platform/src/codat_platform/models/operations/get_supplemental_data_configuration.py index 7b4aaf8f3..4ef873554 100644 --- a/platform/src/codat_platform/models/operations/get_supplemental_data_configuration.py +++ b/platform/src/codat_platform/models/operations/get_supplemental_data_configuration.py @@ -1,57 +1,28 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata + from enum import Enum -import pydantic -from typing_extensions import Annotated, TypedDict class PathParamDataType(str, Enum): - r"""Data types that support supplemental data""" - - CHART_OF_ACCOUNTS = "chartOfAccounts" - BILLS = "bills" - COMPANY = "company" - CREDIT_NOTES = "creditNotes" - CUSTOMERS = "customers" - INVOICES = "invoices" - ITEMS = "items" - JOURNAL_ENTRIES = "journalEntries" - SUPPLIERS = "suppliers" - TAX_RATES = "taxRates" - COMMERCE_COMPANY_INFO = "commerce-companyInfo" - COMMERCE_CUSTOMERS = "commerce-customers" - COMMERCE_DISPUTES = "commerce-disputes" - COMMERCE_LOCATIONS = "commerce-locations" - COMMERCE_ORDERS = "commerce-orders" - COMMERCE_PAYMENTS = "commerce-payments" - COMMERCE_PAYMENT_METHODS = "commerce-paymentMethods" - COMMERCE_PRODUCTS = "commerce-products" - COMMERCE_PRODUCT_CATEGORIES = "commerce-productCategories" - COMMERCE_TAX_COMPONENTS = "commerce-taxComponents" - COMMERCE_TRANSACTIONS = "commerce-transactions" - - -class GetSupplementalDataConfigurationRequestTypedDict(TypedDict): - data_type: PathParamDataType - r"""Supported supplemental data data type.""" - platform_key: str - r"""A unique 4-letter key to represent a platform in each integration.""" - - -class GetSupplementalDataConfigurationRequest(BaseModel): - data_type: Annotated[ - PathParamDataType, - pydantic.Field(alias="dataType"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Supported supplemental data data type.""" - - platform_key: Annotated[ - str, - pydantic.Field(alias="platformKey"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""A unique 4-letter key to represent a platform in each integration.""" + """Operation-parameter enum (lifted from inline OAS enum on get-supplemental-data-configuration).""" + CHART_OF_ACCOUNTS = 'chartOfAccounts' + BILLS = 'bills' + COMPANY = 'company' + CREDIT_NOTES = 'creditNotes' + CUSTOMERS = 'customers' + INVOICES = 'invoices' + ITEMS = 'items' + JOURNAL_ENTRIES = 'journalEntries' + SUPPLIERS = 'suppliers' + TAX_RATES = 'taxRates' + COMMERCE_COMPANY_INFO = 'commerce-companyInfo' + COMMERCE_CUSTOMERS = 'commerce-customers' + COMMERCE_DISPUTES = 'commerce-disputes' + COMMERCE_LOCATIONS = 'commerce-locations' + COMMERCE_ORDERS = 'commerce-orders' + COMMERCE_PAYMENTS = 'commerce-payments' + COMMERCE_PAYMENT_METHODS = 'commerce-paymentMethods' + COMMERCE_PRODUCTS = 'commerce-products' + COMMERCE_PRODUCT_CATEGORIES = 'commerce-productCategories' + COMMERCE_TAX_COMPONENTS = 'commerce-taxComponents' + COMMERCE_TRANSACTIONS = 'commerce-transactions' diff --git a/platform/src/codat_platform/models/operations/list_companies.py b/platform/src/codat_platform/models/operations/list_companies.py index 087d57fbf..a46c02e7f 100644 --- a/platform/src/codat_platform/models/operations/list_companies.py +++ b/platform/src/codat_platform/models/operations/list_companies.py @@ -1,72 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.list_companies — re-export of the list_companies operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, QueryParamMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ListCompaniesRequestTypedDict(TypedDict): - order_by: NotRequired[str] - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - page: NotRequired[int] - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - page_size: NotRequired[int] - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - query: NotRequired[str] - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - tags: NotRequired[str] - r"""Filter companies by tags using the \"equals\" (=), \"not equals\" (!=), and \"contains\" (~) operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying).""" - - -class ListCompaniesRequest(BaseModel): - order_by: Annotated[ - Optional[str], - pydantic.Field(alias="orderBy"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - - page: Annotated[ - Optional[int], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 1 - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - - page_size: Annotated[ - Optional[int], - pydantic.Field(alias="pageSize"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 100 - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - - query: Annotated[ - Optional[str], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - - tags: Annotated[ - Optional[str], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Filter companies by tags using the \"equals\" (=), \"not equals\" (!=), and \"contains\" (~) operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["orderBy", "page", "pageSize", "query", "tags"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_platform.api.companies import ListCompaniesRequest +from codat_platform.api.companies import ListCompaniesRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/list_connections.py b/platform/src/codat_platform/models/operations/list_connections.py index 12d7c6738..0bce31792 100644 --- a/platform/src/codat_platform/models/operations/list_connections.py +++ b/platform/src/codat_platform/models/operations/list_connections.py @@ -1,73 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.list_connections — re-export of the list_connections operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, QueryParamMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ListConnectionsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - order_by: NotRequired[str] - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - page: NotRequired[int] - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - page_size: NotRequired[int] - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - query: NotRequired[str] - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - - -class ListConnectionsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - order_by: Annotated[ - Optional[str], - pydantic.Field(alias="orderBy"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - - page: Annotated[ - Optional[int], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 1 - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - - page_size: Annotated[ - Optional[int], - pydantic.Field(alias="pageSize"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 100 - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - - query: Annotated[ - Optional[str], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["orderBy", "page", "pageSize", "query"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_platform.api.connections import ListConnectionsRequest +from codat_platform.api.connections import ListConnectionsRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/list_custom_data_type_records.py b/platform/src/codat_platform/models/operations/list_custom_data_type_records.py index d2b7f2240..485bdd270 100644 --- a/platform/src/codat_platform/models/operations/list_custom_data_type_records.py +++ b/platform/src/codat_platform/models/operations/list_custom_data_type_records.py @@ -1,74 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.list_custom_data_type_records — re-export of the list_custom_data_type_records operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, QueryParamMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ListCustomDataTypeRecordsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - custom_data_identifier: str - r"""Unique identifier for a custom data type.""" - page: NotRequired[int] - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - page_size: NotRequired[int] - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - - -class ListCustomDataTypeRecordsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - custom_data_identifier: Annotated[ - str, - pydantic.Field(alias="customDataIdentifier"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a custom data type.""" - - page: Annotated[ - Optional[int], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 1 - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - - page_size: Annotated[ - Optional[int], - pydantic.Field(alias="pageSize"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 100 - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["page", "pageSize"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_platform.api.custom_data_type import ListCustomDataTypeRecordsRequest +from codat_platform.api.custom_data_type import ListCustomDataTypeRecordsRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/list_integrations.py b/platform/src/codat_platform/models/operations/list_integrations.py index 2fcd76775..9a487015e 100644 --- a/platform/src/codat_platform/models/operations/list_integrations.py +++ b/platform/src/codat_platform/models/operations/list_integrations.py @@ -1,64 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.list_integrations — re-export of the list_integrations operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, QueryParamMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ListIntegrationsRequestTypedDict(TypedDict): - order_by: NotRequired[str] - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - page: NotRequired[int] - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - page_size: NotRequired[int] - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - query: NotRequired[str] - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - - -class ListIntegrationsRequest(BaseModel): - order_by: Annotated[ - Optional[str], - pydantic.Field(alias="orderBy"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - - page: Annotated[ - Optional[int], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 1 - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - - page_size: Annotated[ - Optional[int], - pydantic.Field(alias="pageSize"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 100 - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - - query: Annotated[ - Optional[str], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["orderBy", "page", "pageSize", "query"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_platform.api.integrations import ListIntegrationsRequest +from codat_platform.api.integrations import ListIntegrationsRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/list_pull_operations.py b/platform/src/codat_platform/models/operations/list_pull_operations.py index 458689b8c..984d58135 100644 --- a/platform/src/codat_platform/models/operations/list_pull_operations.py +++ b/platform/src/codat_platform/models/operations/list_pull_operations.py @@ -1,73 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.list_pull_operations — re-export of the list_pull_operations operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, QueryParamMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ListPullOperationsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - order_by: NotRequired[str] - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - page: NotRequired[int] - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - page_size: NotRequired[int] - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - query: NotRequired[str] - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - - -class ListPullOperationsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - order_by: Annotated[ - Optional[str], - pydantic.Field(alias="orderBy"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - - page: Annotated[ - Optional[int], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 1 - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - - page_size: Annotated[ - Optional[int], - pydantic.Field(alias="pageSize"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 100 - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - - query: Annotated[ - Optional[str], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["orderBy", "page", "pageSize", "query"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_platform.api.refresh_data import ListPullOperationsRequest +from codat_platform.api.refresh_data import ListPullOperationsRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/refresh_company_data.py b/platform/src/codat_platform/models/operations/refresh_company_data.py index 46f6e0a86..3bc659812 100644 --- a/platform/src/codat_platform/models/operations/refresh_company_data.py +++ b/platform/src/codat_platform/models/operations/refresh_company_data.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.refresh_company_data — re-export of the refresh_company_data operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class RefreshCompanyDataRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class RefreshCompanyDataRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" +from codat_platform.api.refresh_data import RefreshCompanyDataRequest +from codat_platform.api.refresh_data import RefreshCompanyDataRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/refresh_custom_data_type.py b/platform/src/codat_platform/models/operations/refresh_custom_data_type.py index 8802da44d..7cdc057cd 100644 --- a/platform/src/codat_platform/models/operations/refresh_custom_data_type.py +++ b/platform/src/codat_platform/models/operations/refresh_custom_data_type.py @@ -1,39 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.refresh_custom_data_type — re-export of the refresh_custom_data_type operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class RefreshCustomDataTypeRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - custom_data_identifier: str - r"""Unique identifier for a custom data type.""" - - -class RefreshCustomDataTypeRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - custom_data_identifier: Annotated[ - str, - pydantic.Field(alias="customDataIdentifier"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a custom data type.""" +from codat_platform.api.custom_data_type import RefreshCustomDataTypeRequest +from codat_platform.api.custom_data_type import RefreshCustomDataTypeRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/refresh_data_type.py b/platform/src/codat_platform/models/operations/refresh_data_type.py index d31e246d4..66611728a 100644 --- a/platform/src/codat_platform/models/operations/refresh_data_type.py +++ b/platform/src/codat_platform/models/operations/refresh_data_type.py @@ -1,58 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.refresh_data_type — re-export of the refresh_data_type operation envelope.""" -from __future__ import annotations -from codat_platform.models.shared import schema_datatype as shared_schema_datatype -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, QueryParamMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class RefreshDataTypeRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - data_type: shared_schema_datatype.SchemaDataType - r"""The key of a Codat data type.""" - connection_id: NotRequired[str] - r"""Optionally, provide a data connection id to only queue pull operations on that connection.""" - - -class RefreshDataTypeRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - data_type: Annotated[ - shared_schema_datatype.SchemaDataType, - pydantic.Field(alias="dataType"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""The key of a Codat data type.""" - - connection_id: Annotated[ - Optional[str], - pydantic.Field(alias="connectionId"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Optionally, provide a data connection id to only queue pull operations on that connection.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["connectionId"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_platform.api.refresh_data import RefreshDataTypeRequest +from codat_platform.api.refresh_data import RefreshDataTypeRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/refresh_product_data.py b/platform/src/codat_platform/models/operations/refresh_product_data.py index 028875929..339526862 100644 --- a/platform/src/codat_platform/models/operations/refresh_product_data.py +++ b/platform/src/codat_platform/models/operations/refresh_product_data.py @@ -1,92 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.refresh_product_data — re-export of the refresh_product_data operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, RequestMetadata -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class RefreshProductDataRequestBodyTypedDict(TypedDict): - r"""Optionally specify one or more data types to refresh for the given custom product. If omitted, the product's scheduled refresh is triggered as usual. When provided, each data type must be valid for the specified product.""" - - data_types: NotRequired[List[str]] - r"""One or more data types to refresh for the product.""" - - -class RefreshProductDataRequestBody(BaseModel): - r"""Optionally specify one or more data types to refresh for the given custom product. If omitted, the product's scheduled refresh is triggered as usual. When provided, each data type must be valid for the specified product.""" - - data_types: Annotated[Optional[List[str]], pydantic.Field(alias="dataTypes")] = None - r"""One or more data types to refresh for the product.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["dataTypes"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m - - -class RefreshProductDataRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - product_identifier: str - r"""Human-readable product identifier for a product.""" - request_body: NotRequired[RefreshProductDataRequestBodyTypedDict] - r"""Optionally specify one or more data types to refresh for the given custom product. If omitted, the product's scheduled refresh is triggered as usual. When provided, each data type must be valid for the specified product.""" - - -class RefreshProductDataRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - product_identifier: Annotated[ - str, - pydantic.Field(alias="productIdentifier"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Human-readable product identifier for a product.""" - - request_body: Annotated[ - Optional[RefreshProductDataRequestBody], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - r"""Optionally specify one or more data types to refresh for the given custom product. If omitted, the product's scheduled refresh is triggered as usual. When provided, each data type must be valid for the specified product.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["RequestBody"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m - - -try: - RefreshProductDataRequestBody.model_rebuild() -except NameError: - pass +from codat_platform.api.companies import RefreshProductDataRequest +from codat_platform.models.refresh_product_data_request import RefreshProductDataRequest as RefreshProductDataRequestBody +from codat_platform.models.refresh_product_data_request import RefreshProductDataRequestTypedDict as RefreshProductDataRequestBodyTypedDict +from codat_platform.api.companies import RefreshProductDataRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/remove_product.py b/platform/src/codat_platform/models/operations/remove_product.py index 46ac60020..34705a5a3 100644 --- a/platform/src/codat_platform/models/operations/remove_product.py +++ b/platform/src/codat_platform/models/operations/remove_product.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.remove_product — re-export of the remove_product operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class RemoveProductRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - product_identifier: str - r"""Human-readable product identifier for a product.""" - - -class RemoveProductRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - product_identifier: Annotated[ - str, - pydantic.Field(alias="productIdentifier"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Human-readable product identifier for a product.""" +from codat_platform.api.companies import RemoveProductRequest +from codat_platform.api.companies import RemoveProductRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/replace_company.py b/platform/src/codat_platform/models/operations/replace_company.py index d82d6a226..e612c1424 100644 --- a/platform/src/codat_platform/models/operations/replace_company.py +++ b/platform/src/codat_platform/models/operations/replace_company.py @@ -1,48 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.replace_company — re-export of the replace_company operation envelope.""" -from __future__ import annotations -from codat_platform.models.shared import companyrequestbody as shared_companyrequestbody -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, RequestMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ReplaceCompanyRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - company_request_body: NotRequired[ - shared_companyrequestbody.CompanyRequestBodyTypedDict - ] - - -class ReplaceCompanyRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - company_request_body: Annotated[ - Optional[shared_companyrequestbody.CompanyRequestBody], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["CompanyRequestBody"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_platform.api.companies import ReplaceCompanyRequest +from codat_platform.api.companies import ReplaceCompanyRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/set_company_syncsettings.py b/platform/src/codat_platform/models/operations/set_company_syncsettings.py index 64a93588c..cc0a8b4e1 100644 --- a/platform/src/codat_platform/models/operations/set_company_syncsettings.py +++ b/platform/src/codat_platform/models/operations/set_company_syncsettings.py @@ -1,102 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.set_company_syncsettings — re-export of the set_company_syncsettings operation envelope.""" -from __future__ import annotations -from codat_platform.models.shared import syncsetting as shared_syncsetting -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, RequestMetadata -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class SetCompanySyncSettingsRequestBodyTypedDict(TypedDict): - r"""Include a `syncSetting` object for each data type. - `syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them. - """ - - company_id: str - r"""Unique identifier for your SMB in Codat.""" - settings: List[shared_syncsetting.SyncSettingTypedDict] - overrides_defaults: NotRequired[bool] - r"""Set to `True` if you want to override default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings).""" - - -class SetCompanySyncSettingsRequestBody(BaseModel): - r"""Include a `syncSetting` object for each data type. - `syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them. - """ - - company_id: Annotated[str, pydantic.Field(alias="companyId")] - r"""Unique identifier for your SMB in Codat.""" - - settings: List[shared_syncsetting.SyncSetting] - - overrides_defaults: Annotated[ - Optional[bool], pydantic.Field(alias="overridesDefaults") - ] = True - r"""Set to `True` if you want to override default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["overridesDefaults"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m - - -class SetCompanySyncSettingsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - request_body: NotRequired[SetCompanySyncSettingsRequestBodyTypedDict] - r"""Include a `syncSetting` object for each data type. - `syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them. - """ - - -class SetCompanySyncSettingsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - request_body: Annotated[ - Optional[SetCompanySyncSettingsRequestBody], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - r"""Include a `syncSetting` object for each data type. - `syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them. - """ - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["RequestBody"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m - - -try: - SetCompanySyncSettingsRequestBody.model_rebuild() -except NameError: - pass +from codat_platform.api.companies import SetCompanySyncSettingsRequest +from codat_platform.models.set_company_sync_settings_request import SetCompanySyncSettingsRequest as SetCompanySyncSettingsRequestBody +from codat_platform.models.set_company_sync_settings_request import SetCompanySyncSettingsRequestTypedDict as SetCompanySyncSettingsRequestBodyTypedDict +from codat_platform.api.companies import SetCompanySyncSettingsRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/unlink_connection.py b/platform/src/codat_platform/models/operations/unlink_connection.py index 08865e03c..46e98fb65 100644 --- a/platform/src/codat_platform/models/operations/unlink_connection.py +++ b/platform/src/codat_platform/models/operations/unlink_connection.py @@ -1,59 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.unlink_connection — re-export of the unlink_connection operation envelope.""" -from __future__ import annotations -from codat_platform.models.shared import ( - updateconnectionstatus as shared_updateconnectionstatus, -) -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, RequestMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class UnlinkConnectionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - update_connection_status: NotRequired[ - shared_updateconnectionstatus.UpdateConnectionStatusTypedDict - ] - - -class UnlinkConnectionRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - update_connection_status: Annotated[ - Optional[shared_updateconnectionstatus.UpdateConnectionStatus], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["UpdateConnectionStatus"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_platform.api.connections import UnlinkConnectionRequest +from codat_platform.api.connections import UnlinkConnectionRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/update_company.py b/platform/src/codat_platform/models/operations/update_company.py index dfd4433c8..85a34ab1a 100644 --- a/platform/src/codat_platform/models/operations/update_company.py +++ b/platform/src/codat_platform/models/operations/update_company.py @@ -1,50 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.update_company — re-export of the update_company operation envelope.""" -from __future__ import annotations -from codat_platform.models.shared import ( - companyupdaterequest as shared_companyupdaterequest, -) -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, RequestMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class UpdateCompanyRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - company_update_request: NotRequired[ - shared_companyupdaterequest.CompanyUpdateRequestTypedDict - ] - - -class UpdateCompanyRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - company_update_request: Annotated[ - Optional[shared_companyupdaterequest.CompanyUpdateRequest], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["CompanyUpdateRequest"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_platform.api.companies import UpdateCompanyRequest +from codat_platform.api.companies import UpdateCompanyRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/update_connection_authorization.py b/platform/src/codat_platform/models/operations/update_connection_authorization.py index aa76da47a..ab8fa66d5 100644 --- a/platform/src/codat_platform/models/operations/update_connection_authorization.py +++ b/platform/src/codat_platform/models/operations/update_connection_authorization.py @@ -1,54 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.update_connection_authorization — re-export of the update_connection_authorization operation envelope.""" -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from codat_platform.utils import FieldMetadata, PathParamMetadata, RequestMetadata -import pydantic -from pydantic import model_serializer -from typing import Dict, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class UpdateConnectionAuthorizationRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - request_body: NotRequired[Dict[str, str]] - - -class UpdateConnectionAuthorizationRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - request_body: Annotated[ - Optional[Dict[str, str]], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["RequestBody"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_platform.api.connections import UpdateConnectionAuthorizationRequest +from codat_platform.api.connections import UpdateConnectionAuthorizationRequestTypedDict diff --git a/platform/src/codat_platform/models/operations/update_profile_syncsettings.py b/platform/src/codat_platform/models/operations/update_profile_syncsettings.py index 29ab4252b..e5943e10b 100644 --- a/platform/src/codat_platform/models/operations/update_profile_syncsettings.py +++ b/platform/src/codat_platform/models/operations/update_profile_syncsettings.py @@ -1,59 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.operations.update_profile_syncsettings — re-export of the update_profile_syncsettings operation envelope.""" -from __future__ import annotations -from codat_platform.models.shared import syncsetting as shared_syncsetting -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class UpdateProfileSyncSettingsRequestBodyTypedDict(TypedDict): - r"""Include a `syncSetting` object for each data type. - `syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them. - """ - - client_id: str - r"""Unique identifier for your client in Codat.""" - settings: List[shared_syncsetting.SyncSettingTypedDict] - overrides_defaults: NotRequired[bool] - r"""Set to `True` if you want to override default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings).""" - - -class UpdateProfileSyncSettingsRequestBody(BaseModel): - r"""Include a `syncSetting` object for each data type. - `syncFromWindow`, `syncFromUTC` & `monthsToSync` only need to be included if you wish to set a value for them. - """ - - client_id: Annotated[str, pydantic.Field(alias="clientId")] - r"""Unique identifier for your client in Codat.""" - - settings: List[shared_syncsetting.SyncSetting] - - overrides_defaults: Annotated[ - Optional[bool], pydantic.Field(alias="overridesDefaults") - ] = True - r"""Set to `True` if you want to override default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["overridesDefaults"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m - - -try: - UpdateProfileSyncSettingsRequestBody.model_rebuild() -except NameError: - pass +from codat_platform.models.update_profile_sync_settings_request import UpdateProfileSyncSettingsRequestBody +from codat_platform.api.settings import UpdateProfileSyncSettingsRequestBodyTypedDict diff --git a/platform/src/codat_platform/models/paging_info.py b/platform/src/codat_platform/models/paging_info.py new file mode 100644 index 000000000..5588849ba --- /dev/null +++ b/platform/src/codat_platform/models/paging_info.py @@ -0,0 +1,113 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.links import Links, LinksTypedDict +from typing import Optional, Set +from typing_extensions import Self + +class PagingInfo(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + PagingInfo + """ # noqa: E501 + page_number: int = Field(description="Current page number.", alias="pageNumber") + page_size: int = Field(description="Number of items to return in results array.", alias="pageSize") + total_results: int = Field(description="Total number of items.", alias="totalResults") + links: Links = Field(alias="_links") + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PagingInfo from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['_links'] = self.links.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PagingInfo from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "pageNumber": obj.get("pageNumber"), + "pageSize": obj.get("pageSize"), + "totalResults": obj.get("totalResults"), + "_links": Links.from_dict(obj["_links"]) if obj.get("_links") is not None else None + }) + return _obj + + + + + +class PagingInfoTypedDict(TypedDict): + """TypedDict variant of PagingInfo, for dict-literal request/response inputs.""" + page_number: NotRequired[int] + page_size: NotRequired[int] + total_results: NotRequired[int] + links: NotRequired[LinksTypedDict] diff --git a/platform/src/codat_platform/models/refresh_product_data_request.py b/platform/src/codat_platform/models/refresh_product_data_request.py new file mode 100644 index 000000000..bf44f1e4c --- /dev/null +++ b/platform/src/codat_platform/models/refresh_product_data_request.py @@ -0,0 +1,113 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class RefreshProductDataRequest(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + RefreshProductDataRequest + """ # noqa: E501 + data_types: Optional[List[str]] = Field(default=None, description="One or more data types to refresh for the product.", alias="dataTypes") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["dataTypes"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of RefreshProductDataRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of RefreshProductDataRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "dataTypes": obj.get("dataTypes") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + + + + +class RefreshProductDataRequestTypedDict(TypedDict): + """TypedDict variant of RefreshProductDataRequest, for dict-literal request/response inputs.""" + data_types: NotRequired[Optional[List[str]]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/platform/src/codat_platform/models/set_company_sync_settings_request.py b/platform/src/codat_platform/models/set_company_sync_settings_request.py new file mode 100644 index 000000000..52688d40c --- /dev/null +++ b/platform/src/codat_platform/models/set_company_sync_settings_request.py @@ -0,0 +1,113 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List +from codat_platform.models.shared.syncsetting import SyncSetting, SyncSettingTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class SetCompanySyncSettingsRequest(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + SetCompanySyncSettingsRequest + """ # noqa: E501 + company_id: str = Field(description="Unique identifier for your SMB in Codat.", alias="companyId") + settings: List[SyncSetting] + overrides_defaults: Optional[bool] = Field(default=True, description="Set to `True` if you want to override default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings).", alias="overridesDefaults") + __properties: ClassVar[List[str]] = ["companyId", "settings", "overridesDefaults"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SetCompanySyncSettingsRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in settings (list) + _items = [] + if self.settings: + for _item_settings in self.settings: + if _item_settings: + _items.append(_item_settings.to_dict()) + _dict['settings'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SetCompanySyncSettingsRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "companyId": obj.get("companyId"), + "settings": [SyncSetting.from_dict(_item) for _item in obj["settings"]] if obj.get("settings") is not None else None, + "overridesDefaults": obj.get("overridesDefaults") if obj.get("overridesDefaults") is not None else True + }) + return _obj + + + + + +class SetCompanySyncSettingsRequestTypedDict(TypedDict): + """TypedDict variant of SetCompanySyncSettingsRequest, for dict-literal request/response inputs.""" + company_id: NotRequired[str] + settings: List[SyncSettingTypedDict] + overrides_defaults: NotRequired[bool] diff --git a/platform/src/codat_platform/models/shared/__init__.py b/platform/src/codat_platform/models/shared/__init__.py index fba41c37a..9128318b3 100644 --- a/platform/src/codat_platform/models/shared/__init__.py +++ b/platform/src/codat_platform/models/shared/__init__.py @@ -1,506 +1,411 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.models.shared — domain-shared models.""" -from typing import Any, TYPE_CHECKING - -from codat_platform.utils.dynamic_imports import lazy_getattr, lazy_dir +from importlib import import_module +from typing import TYPE_CHECKING if TYPE_CHECKING: - from .apikeydetails import APIKeyDetails, APIKeyDetailsTypedDict - from .apikeys import APIKeys, APIKeysTypedDict - from .branding import Branding, BrandingTypedDict - from .brandingbutton import BrandingButton, BrandingButtonTypedDict - from .brandingimage import BrandingImage, BrandingImageTypedDict - from .brandinglogo import BrandingLogo, BrandingLogoTypedDict - from .clientratelimitwebhook import ( - ClientRateLimitWebhook, - ClientRateLimitWebhookTypedDict, - ) - from .clientratelimitwebhookpayload import ( - ClientRateLimitWebhookPayload, - ClientRateLimitWebhookPayloadTypedDict, - ) - from .companies import Companies, CompaniesTypedDict - from .company import Company, CompanyTypedDict - from .companyaccesstoken import CompanyAccessToken, CompanyAccessTokenTypedDict - from .companydetails import CompanyDetails, CompanyDetailsTypedDict - from .companyreference import ( - CompanyReference, - CompanyReferenceLinks, - CompanyReferenceLinksTypedDict, - CompanyReferenceTypedDict, - ) - from .companyrequestbody import CompanyRequestBody, CompanyRequestBodyTypedDict - from .companysyncsettings import CompanySyncSettings, CompanySyncSettingsTypedDict - from .companyupdaterequest import ( - CompanyUpdateRequest, - CompanyUpdateRequestTypedDict, - ) - from .companywebhook import CompanyWebhook, CompanyWebhookTypedDict - from .connection import Connection, ConnectionTypedDict - from .connectionmanagementaccesstoken import ( - ConnectionManagementAccessToken, - ConnectionManagementAccessTokenTypedDict, - ) - from .connectionmanagementallowedorigins import ( - ConnectionManagementAllowedOrigins, - ConnectionManagementAllowedOriginsTypedDict, - ) - from .connections import Connections, ConnectionsTypedDict - from .connectionwebhook import ConnectionWebhook, ConnectionWebhookTypedDict - from .connectionwebhookpayload import ( - ConnectionWebhookPayload, - ConnectionWebhookPayloadTypedDict, - ) - from .createapikey import CreateAPIKey, CreateAPIKeyTypedDict - from .customdatatypeconfiguration import ( - CustomDataTypeConfiguration, - CustomDataTypeConfigurationTypedDict, - ) - from .customdatatyperecord import ( - Content, - ContentTypedDict, - CustomDataTypeRecord, - CustomDataTypeRecordTypedDict, - ModifiedDate, - ModifiedDateTypedDict, - ) - from .customdatatyperecords import ( - CustomDataTypeRecords, - CustomDataTypeRecordsTypedDict, - ) - from .dataconnectionerror import ( - DataConnectionError, - DataConnectionErrorTypedDict, - ErrorStatus, - ) - from .dataconnectionstatus import DataConnectionStatus - from .datastatus import DataStatus, DataStatusTypedDict, DataTypes - from .datastatuses import DataStatuses, DataStatusesTypedDict - from .datatype import DataType - from .datatypefeature import DataTypeFeature, DataTypeFeatureTypedDict - from .datatypereadsummary import DataTypeReadSummary, DataTypeReadSummaryTypedDict - from .datatypewritewebhook import ( - DataTypeWriteWebhook, - DataTypeWriteWebhookTypedDict, - ) - from .datatypewritewebhookpayload import ( - DataTypeWriteWebhookPayload, - DataTypeWriteWebhookPayloadTypedDict, - ) - from .datatypewritewebhookrecord import ( - DataTypeWriteWebhookRecord, - DataTypeWriteWebhookRecordTypedDict, - ) - from .errormessage import ErrorMessage, ErrorMessageTypedDict - from .errorvalidation import ErrorValidation, ErrorValidationTypedDict - from .errorvalidationitem import ErrorValidationItem, ErrorValidationItemTypedDict - from .featurestate import FeatureState - from .featuretype import FeatureType - from .halref import HalRef, HalRefTypedDict - from .imagereference import ImageReference, ImageReferenceTypedDict - from .integration import Integration, IntegrationTypedDict - from .integrations import Integrations, IntegrationsTypedDict - from .issue import Issue, IssueLinks, IssueLinksTypedDict, IssueTypedDict - from .links import Links, LinksTypedDict - from .profile import Profile, ProfileTypedDict - from .pulloperation import DatasetStatus, PullOperation, PullOperationTypedDict - from .pulloperations import PullOperations, PullOperationsTypedDict - from .pushchangetype import PushChangeType - from .pushfieldvalidation import PushFieldValidation, PushFieldValidationTypedDict - from .pushoperation import PushOperation, PushOperationTypedDict - from .pushoperationchange import PushOperationChange, PushOperationChangeTypedDict - from .pushoperationref import PushOperationRef, PushOperationRefTypedDict - from .pushoperations import PushOperations, PushOperationsTypedDict - from .pushoperationstatus import PushOperationStatus - from .pushoption import PushOption, PushOptionTypedDict - from .pushoptionchoice import PushOptionChoice, PushOptionChoiceTypedDict - from .pushoptionproperty import PushOptionProperty, PushOptionPropertyTypedDict - from .pushoptiontype import PushOptionType - from .pushvalidationinfo import PushValidationInfo, PushValidationInfoTypedDict - from .readcompletedwebhook import ( - ReadCompletedWebhook, - ReadCompletedWebhookTypedDict, - ) - from .readcompletedwebhookpayload import ( - ReadCompletedWebhookPayload, - ReadCompletedWebhookPayloadTypedDict, - ) - from .schema_datatype import SchemaDataType from .security import Security, SecurityTypedDict - from .sourcetype import SourceType - from .status import Status - from .supplementaldataconfiguration import ( - SupplementalDataConfiguration, - SupplementalDataConfigurationTypedDict, - SupplementalDataSourceConfiguration, - SupplementalDataSourceConfigurationTypedDict, - ) - from .supportedfeature import SupportedFeature, SupportedFeatureTypedDict - from .syncsetting import SyncSetting, SyncSettingTypedDict - from .syncsettings import SyncSettings, SyncSettingsTypedDict - from .updateconnectionstatus import ( - UpdateConnectionStatus, - UpdateConnectionStatusTypedDict, - ) - from .validation import Validation, ValidationTypedDict - from .validationitem import ValidationItem, ValidationItemTypedDict - from .validationitem1 import ValidationItem1, ValidationItem1TypedDict - from .validationresult import ValidationResult, ValidationResultTypedDict - from .webhookconsumer import WebhookConsumer, WebhookConsumerTypedDict - from .webhookconsumerprototype import ( - WebhookConsumerPrototype, - WebhookConsumerPrototypeTypedDict, - ) - from .webhookconsumers import WebhookConsumers, WebhookConsumersTypedDict - from .writestatus import WriteStatus - from .writetype import WriteType - -__all__ = [ - "APIKeyDetails", - "APIKeyDetailsTypedDict", - "APIKeys", - "APIKeysTypedDict", - "Branding", - "BrandingButton", - "BrandingButtonTypedDict", - "BrandingImage", - "BrandingImageTypedDict", - "BrandingLogo", - "BrandingLogoTypedDict", - "BrandingTypedDict", - "ClientRateLimitWebhook", - "ClientRateLimitWebhookPayload", - "ClientRateLimitWebhookPayloadTypedDict", - "ClientRateLimitWebhookTypedDict", - "Companies", - "CompaniesTypedDict", - "Company", - "CompanyAccessToken", - "CompanyAccessTokenTypedDict", - "CompanyDetails", - "CompanyDetailsTypedDict", - "CompanyReference", - "CompanyReferenceLinks", - "CompanyReferenceLinksTypedDict", - "CompanyReferenceTypedDict", - "CompanyRequestBody", - "CompanyRequestBodyTypedDict", - "CompanySyncSettings", - "CompanySyncSettingsTypedDict", - "CompanyTypedDict", - "CompanyUpdateRequest", - "CompanyUpdateRequestTypedDict", - "CompanyWebhook", - "CompanyWebhookTypedDict", - "Connection", - "ConnectionManagementAccessToken", - "ConnectionManagementAccessTokenTypedDict", - "ConnectionManagementAllowedOrigins", - "ConnectionManagementAllowedOriginsTypedDict", - "ConnectionTypedDict", - "ConnectionWebhook", - "ConnectionWebhookPayload", - "ConnectionWebhookPayloadTypedDict", - "ConnectionWebhookTypedDict", - "Connections", - "ConnectionsTypedDict", - "Content", - "ContentTypedDict", - "CreateAPIKey", - "CreateAPIKeyTypedDict", - "CustomDataTypeConfiguration", - "CustomDataTypeConfigurationTypedDict", - "CustomDataTypeRecord", - "CustomDataTypeRecordTypedDict", - "CustomDataTypeRecords", - "CustomDataTypeRecordsTypedDict", - "DataConnectionError", - "DataConnectionErrorTypedDict", - "DataConnectionStatus", - "DataStatus", - "DataStatusTypedDict", - "DataStatuses", - "DataStatusesTypedDict", - "DataType", - "DataTypeFeature", - "DataTypeFeatureTypedDict", - "DataTypeReadSummary", - "DataTypeReadSummaryTypedDict", - "DataTypeWriteWebhook", - "DataTypeWriteWebhookPayload", - "DataTypeWriteWebhookPayloadTypedDict", - "DataTypeWriteWebhookRecord", - "DataTypeWriteWebhookRecordTypedDict", - "DataTypeWriteWebhookTypedDict", - "DataTypes", - "DatasetStatus", - "ErrorMessage", - "ErrorMessageTypedDict", - "ErrorStatus", - "ErrorValidation", - "ErrorValidationItem", - "ErrorValidationItemTypedDict", - "ErrorValidationTypedDict", - "FeatureState", - "FeatureType", - "HalRef", - "HalRefTypedDict", - "ImageReference", - "ImageReferenceTypedDict", - "Integration", - "IntegrationTypedDict", - "Integrations", - "IntegrationsTypedDict", - "Issue", - "IssueLinks", - "IssueLinksTypedDict", - "IssueTypedDict", - "Links", - "LinksTypedDict", - "ModifiedDate", - "ModifiedDateTypedDict", - "Profile", - "ProfileTypedDict", - "PullOperation", - "PullOperationTypedDict", - "PullOperations", - "PullOperationsTypedDict", - "PushChangeType", - "PushFieldValidation", - "PushFieldValidationTypedDict", - "PushOperation", - "PushOperationChange", - "PushOperationChangeTypedDict", - "PushOperationRef", - "PushOperationRefTypedDict", - "PushOperationStatus", - "PushOperationTypedDict", - "PushOperations", - "PushOperationsTypedDict", - "PushOption", - "PushOptionChoice", - "PushOptionChoiceTypedDict", - "PushOptionProperty", - "PushOptionPropertyTypedDict", - "PushOptionType", - "PushOptionTypedDict", - "PushValidationInfo", - "PushValidationInfoTypedDict", - "ReadCompletedWebhook", - "ReadCompletedWebhookPayload", - "ReadCompletedWebhookPayloadTypedDict", - "ReadCompletedWebhookTypedDict", - "SchemaDataType", - "Security", - "SecurityTypedDict", - "SourceType", - "Status", - "SupplementalDataConfiguration", - "SupplementalDataConfigurationTypedDict", - "SupplementalDataSourceConfiguration", - "SupplementalDataSourceConfigurationTypedDict", - "SupportedFeature", - "SupportedFeatureTypedDict", - "SyncSetting", - "SyncSettingTypedDict", - "SyncSettings", - "SyncSettingsTypedDict", - "UpdateConnectionStatus", - "UpdateConnectionStatusTypedDict", - "Validation", - "ValidationItem", - "ValidationItem1", - "ValidationItem1TypedDict", - "ValidationItemTypedDict", - "ValidationResult", - "ValidationResultTypedDict", - "ValidationTypedDict", - "WebhookConsumer", - "WebhookConsumerPrototype", - "WebhookConsumerPrototypeTypedDict", - "WebhookConsumerTypedDict", - "WebhookConsumers", - "WebhookConsumersTypedDict", - "WriteStatus", - "WriteType", -] + from codat_platform.models.access_token import AccessToken, AccessTokenTypedDict + from codat_platform.models.shared.apikeydetails import APIKeyDetails, APIKeyDetailsTypedDict + from codat_platform.models.shared.apikeydetails import APIKeyDetailsTypedDict as ApiKeyDetailsTypedDict + from codat_platform.models.shared.apikeydetails import APIKeyDetails as ApiKeyDetails + from codat_platform.models.shared.apikeys import APIKeys, APIKeysTypedDict + from codat_platform.models.shared.apikeys import APIKeysTypedDict as ApiKeysTypedDict + from codat_platform.models.shared.apikeys import APIKeys as ApiKeys + from codat_platform.models.shared.branding import Branding, BrandingTypedDict + from codat_platform.models.shared.brandingbutton import BrandingButton, BrandingButtonTypedDict + from codat_platform.models.shared.brandingimage import BrandingImage, BrandingImageTypedDict + from codat_platform.models.shared.brandinglogo import BrandingLogo, BrandingLogoTypedDict + from codat_platform.models.shared.clientratelimitwebhook import ClientRateLimitWebhook, ClientRateLimitWebhookTypedDict + from codat_platform.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayload, ClientRateLimitWebhookPayloadTypedDict + from codat_platform.models.shared.companies import Companies, CompaniesTypedDict + from codat_platform.models.shared.company import Company, CompanyTypedDict + from codat_platform.models.shared.companyaccesstoken import CompanyAccessToken, CompanyAccessTokenTypedDict + from codat_platform.models.shared.companydetails import CompanyDetails, CompanyDetailsTypedDict + from codat_platform.models.company_product_webhook import CompanyProductWebhook, CompanyProductWebhookTypedDict + from codat_platform.models.company_product_webhook_payload import CompanyProductWebhookPayload, CompanyProductWebhookPayloadTypedDict + from codat_platform.models.shared.companyreference import CompanyReference, CompanyReferenceTypedDict + from codat_platform.models.company_reference_links import CompanyReferenceLinks, CompanyReferenceLinksTypedDict + from codat_platform.models.shared.companyrequestbody import CompanyRequestBody, CompanyRequestBodyTypedDict + from codat_platform.models.shared.companysyncsettings import CompanySyncSettings, CompanySyncSettingsTypedDict + from codat_platform.models.shared.companyupdaterequest import CompanyUpdateRequest, CompanyUpdateRequestTypedDict + from codat_platform.models.shared.companywebhook import CompanyWebhook, CompanyWebhookTypedDict + from codat_platform.models.shared.connection import Connection, ConnectionTypedDict + from codat_platform.models.shared.connectionmanagementaccesstoken import ConnectionManagementAccessToken, ConnectionManagementAccessTokenTypedDict + from codat_platform.models.shared.connectionmanagementallowedorigins import ConnectionManagementAllowedOrigins, ConnectionManagementAllowedOriginsTypedDict + from codat_platform.models.shared.connectionwebhook import ConnectionWebhook, ConnectionWebhookTypedDict + from codat_platform.models.shared.connectionwebhookpayload import ConnectionWebhookPayload, ConnectionWebhookPayloadTypedDict + from codat_platform.models.shared.connections import Connections, ConnectionsTypedDict + from codat_platform.models.shared.createapikey import CreateAPIKey, CreateAPIKeyTypedDict + from codat_platform.models.shared.createapikey import CreateAPIKeyTypedDict as CreateApiKeyTypedDict + from codat_platform.models.shared.createapikey import CreateAPIKey as CreateApiKey + from codat_platform.models.create_connection_request import CreateConnectionRequest, CreateConnectionRequestTypedDict + from codat_platform.models.current_status import CurrentStatus + from codat_platform.models.shared.customdatatypeconfiguration import CustomDataTypeConfiguration, CustomDataTypeConfigurationTypedDict + from codat_platform.models.shared.customdatatyperecord import CustomDataTypeRecord, CustomDataTypeRecordTypedDict + from codat_platform.models.shared.customdatatyperecords import CustomDataTypeRecords, CustomDataTypeRecordsTypedDict + from codat_platform.models.shared.dataconnectionerror import DataConnectionError, DataConnectionErrorTypedDict + from codat_platform.models.shared.dataconnectionstatus import DataConnectionStatus + from codat_platform.models.shared.datastatus import DataStatus, DataStatusTypedDict + from codat_platform.models.shared.datastatuses import DataStatuses, DataStatusesTypedDict + from codat_platform.models.shared.datatype import DataType + from codat_platform.models.shared.datatypefeature import DataTypeFeature, DataTypeFeatureTypedDict + from codat_platform.models.shared.datatypereadsummary import DataTypeReadSummary, DataTypeReadSummaryTypedDict + from codat_platform.models.shared.datatypewritewebhook import DataTypeWriteWebhook, DataTypeWriteWebhookTypedDict + from codat_platform.models.shared.datatypewritewebhookpayload import DataTypeWriteWebhookPayload, DataTypeWriteWebhookPayloadTypedDict + from codat_platform.models.shared.datatypewritewebhookrecord import DataTypeWriteWebhookRecord, DataTypeWriteWebhookRecordTypedDict + from codat_platform.models.data_types import DataTypes + from codat_platform.models.dataset_status import DatasetStatus + from codat_platform.models.shared.errormessage import ErrorMessage, ErrorMessageTypedDict + from codat_platform.models.error_status import ErrorStatus + from codat_platform.models.shared.errorvalidation import ErrorValidation, ErrorValidationTypedDict + from codat_platform.models.shared.errorvalidationitem import ErrorValidationItem, ErrorValidationItemTypedDict + from codat_platform.models.shared.featurestate import FeatureState + from codat_platform.models.shared.featuretype import FeatureType + from codat_platform.models.shared.halref import HalRef, HalRefTypedDict + from codat_platform.models.shared.imagereference import ImageReference, ImageReferenceTypedDict + from codat_platform.models.shared.integration import Integration, IntegrationTypedDict + from codat_platform.models.shared.integrations import Integrations, IntegrationsTypedDict + from codat_platform.models.shared.issue import Issue, IssueTypedDict + from codat_platform.models.issue_links import IssueLinks, IssueLinksTypedDict + from codat_platform.models.shared.links import Links, LinksTypedDict + from codat_platform.models.modified_date import ModifiedDate, ModifiedDateTypedDict + from codat_platform.models.paging_info import PagingInfo, PagingInfoTypedDict + from codat_platform.models.shared.profile import Profile, ProfileTypedDict + from codat_platform.models.shared.pulloperation import PullOperation, PullOperationTypedDict + from codat_platform.models.shared.pulloperations import PullOperations, PullOperationsTypedDict + from codat_platform.models.shared.pushchangetype import PushChangeType + from codat_platform.models.shared.pushfieldvalidation import PushFieldValidation, PushFieldValidationTypedDict + from codat_platform.models.shared.pushoperation import PushOperation, PushOperationTypedDict + from codat_platform.models.shared.pushoperationchange import PushOperationChange, PushOperationChangeTypedDict + from codat_platform.models.shared.pushoperationref import PushOperationRef, PushOperationRefTypedDict + from codat_platform.models.shared.pushoperationstatus import PushOperationStatus + from codat_platform.models.shared.pushoperations import PushOperations, PushOperationsTypedDict + from codat_platform.models.shared.pushoption import PushOption, PushOptionTypedDict + from codat_platform.models.shared.pushoptionchoice import PushOptionChoice, PushOptionChoiceTypedDict + from codat_platform.models.shared.pushoptionproperty import PushOptionProperty, PushOptionPropertyTypedDict + from codat_platform.models.shared.pushoptiontype import PushOptionType + from codat_platform.models.shared.pushvalidationinfo import PushValidationInfo, PushValidationInfoTypedDict + from codat_platform.models.shared.readcompletedwebhook import ReadCompletedWebhook, ReadCompletedWebhookTypedDict + from codat_platform.models.shared.readcompletedwebhookpayload import ReadCompletedWebhookPayload, ReadCompletedWebhookPayloadTypedDict + from codat_platform.models.refresh_product_data_request import RefreshProductDataRequest, RefreshProductDataRequestTypedDict + from codat_platform.models.set_company_sync_settings_request import SetCompanySyncSettingsRequest, SetCompanySyncSettingsRequestTypedDict + from codat_platform.models.shared.sourcetype import SourceType + from codat_platform.models.shared.status import Status + from codat_platform.models.shared.supplementaldataconfiguration import SupplementalDataConfiguration, SupplementalDataConfigurationTypedDict + from codat_platform.models.supplemental_data_source_configuration import SupplementalDataSourceConfiguration, SupplementalDataSourceConfigurationTypedDict + from codat_platform.models.shared.supportedfeature import SupportedFeature, SupportedFeatureTypedDict + from codat_platform.models.shared.syncsetting import SyncSetting, SyncSettingTypedDict + from codat_platform.models.shared.syncsettings import SyncSettings, SyncSettingsTypedDict + from codat_platform.models.shared.updateconnectionstatus import UpdateConnectionStatus, UpdateConnectionStatusTypedDict + from codat_platform.models.update_profile_sync_settings_request import UpdateProfileSyncSettingsRequest, UpdateProfileSyncSettingsRequestTypedDict + from codat_platform.models.shared.validation import Validation, ValidationTypedDict + from codat_platform.models.shared.validationitem import ValidationItem, ValidationItemTypedDict + from codat_platform.models.validation_item1 import ValidationItem1, ValidationItem1TypedDict + from codat_platform.models.shared.validationresult import ValidationResult, ValidationResultTypedDict + from codat_platform.models.shared.webhookconsumer import WebhookConsumer, WebhookConsumerTypedDict + from codat_platform.models.shared.webhookconsumerprototype import WebhookConsumerPrototype, WebhookConsumerPrototypeTypedDict + from codat_platform.models.shared.webhookconsumers import WebhookConsumers, WebhookConsumersTypedDict + from codat_platform.models.webhook_zapier_key import WebhookZapierKey, WebhookZapierKeyTypedDict + from codat_platform.models.shared.writestatus import WriteStatus + from codat_platform.models.shared.writetype import WriteType + from codat_platform.models.shared.schema_datatype import SchemaDataType + from codat_platform.models.shared.brandingbutton import BrandingButtonTypedDict as BrandingButtonTypedDict + from codat_platform.models.shared.brandingimage import BrandingImageTypedDict as BrandingImageTypedDict + from codat_platform.models.shared.brandinglogo import BrandingLogoTypedDict as BrandingLogoTypedDict + from codat_platform.models.shared.branding import BrandingTypedDict as BrandingTypedDict + from codat_platform.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayloadTypedDict as ClientRateLimitWebhookPayloadTypedDict + from codat_platform.models.shared.clientratelimitwebhook import ClientRateLimitWebhookTypedDict as ClientRateLimitWebhookTypedDict + from codat_platform.models.shared.companies import CompaniesTypedDict as CompaniesTypedDict + from codat_platform.models.shared.companyaccesstoken import CompanyAccessTokenTypedDict as CompanyAccessTokenTypedDict + from codat_platform.models.shared.companydetails import CompanyDetailsTypedDict as CompanyDetailsTypedDict + from codat_platform.models.company_reference_links import CompanyReferenceLinksTypedDict as CompanyReferenceLinksTypedDict + from codat_platform.models.shared.companyreference import CompanyReferenceTypedDict as CompanyReferenceTypedDict + from codat_platform.models.shared.companyrequestbody import CompanyRequestBodyTypedDict as CompanyRequestBodyTypedDict + from codat_platform.models.shared.companysyncsettings import CompanySyncSettingsTypedDict as CompanySyncSettingsTypedDict + from codat_platform.models.shared.company import CompanyTypedDict as CompanyTypedDict + from codat_platform.models.shared.companyupdaterequest import CompanyUpdateRequestTypedDict as CompanyUpdateRequestTypedDict + from codat_platform.models.shared.companywebhook import CompanyWebhookTypedDict as CompanyWebhookTypedDict + from codat_platform.models.shared.connectionmanagementaccesstoken import ConnectionManagementAccessTokenTypedDict as ConnectionManagementAccessTokenTypedDict + from codat_platform.models.shared.connectionmanagementallowedorigins import ConnectionManagementAllowedOriginsTypedDict as ConnectionManagementAllowedOriginsTypedDict + from codat_platform.models.shared.connection import ConnectionTypedDict as ConnectionTypedDict + from codat_platform.models.shared.connectionwebhookpayload import ConnectionWebhookPayloadTypedDict as ConnectionWebhookPayloadTypedDict + from codat_platform.models.shared.connectionwebhook import ConnectionWebhookTypedDict as ConnectionWebhookTypedDict + from codat_platform.models.shared.connections import ConnectionsTypedDict as ConnectionsTypedDict + from codat_platform.models.shared.customdatatypeconfiguration import CustomDataTypeConfigurationTypedDict as CustomDataTypeConfigurationTypedDict + from codat_platform.models.shared.customdatatyperecord import CustomDataTypeRecordTypedDict as CustomDataTypeRecordTypedDict + from codat_platform.models.shared.customdatatyperecords import CustomDataTypeRecordsTypedDict as CustomDataTypeRecordsTypedDict + from codat_platform.models.shared.dataconnectionerror import DataConnectionErrorTypedDict as DataConnectionErrorTypedDict + from codat_platform.models.shared.dataconnectionstatus import DataConnectionStatus as DataConnectionStatus + from codat_platform.models.shared.datastatus import DataStatusTypedDict as DataStatusTypedDict + from codat_platform.models.shared.datastatuses import DataStatusesTypedDict as DataStatusesTypedDict + from codat_platform.models.shared.datatypefeature import DataTypeFeatureTypedDict as DataTypeFeatureTypedDict + from codat_platform.models.shared.datatypereadsummary import DataTypeReadSummaryTypedDict as DataTypeReadSummaryTypedDict + from codat_platform.models.shared.datatypewritewebhookpayload import DataTypeWriteWebhookPayloadTypedDict as DataTypeWriteWebhookPayloadTypedDict + from codat_platform.models.shared.datatypewritewebhookrecord import DataTypeWriteWebhookRecordTypedDict as DataTypeWriteWebhookRecordTypedDict + from codat_platform.models.shared.datatypewritewebhook import DataTypeWriteWebhookTypedDict as DataTypeWriteWebhookTypedDict + from codat_platform.models.data_types import DataTypes as DataTypes + from codat_platform.models.dataset_status import DatasetStatus as DatasetStatus + from codat_platform.models.shared.errormessage import ErrorMessageTypedDict as ErrorMessageTypedDict + from codat_platform.models.error_status import ErrorStatus as ErrorStatus + from codat_platform.models.shared.errorvalidationitem import ErrorValidationItemTypedDict as ErrorValidationItemTypedDict + from codat_platform.models.shared.errorvalidation import ErrorValidationTypedDict as ErrorValidationTypedDict + from codat_platform.models.shared.featurestate import FeatureState as FeatureState + from codat_platform.models.shared.featuretype import FeatureType as FeatureType + from codat_platform.models.shared.halref import HalRefTypedDict as HalRefTypedDict + from codat_platform.models.shared.imagereference import ImageReferenceTypedDict as ImageReferenceTypedDict + from codat_platform.models.shared.integration import IntegrationTypedDict as IntegrationTypedDict + from codat_platform.models.shared.integrations import IntegrationsTypedDict as IntegrationsTypedDict + from codat_platform.models.issue_links import IssueLinksTypedDict as IssueLinksTypedDict + from codat_platform.models.shared.issue import IssueTypedDict as IssueTypedDict + from codat_platform.models.shared.links import LinksTypedDict as LinksTypedDict + from codat_platform.models.modified_date import ModifiedDateTypedDict as ModifiedDateTypedDict + from codat_platform.models.shared.profile import ProfileTypedDict as ProfileTypedDict + from codat_platform.models.shared.pulloperation import PullOperationTypedDict as PullOperationTypedDict + from codat_platform.models.shared.pulloperations import PullOperationsTypedDict as PullOperationsTypedDict + from codat_platform.models.shared.pushchangetype import PushChangeType as PushChangeType + from codat_platform.models.shared.pushfieldvalidation import PushFieldValidationTypedDict as PushFieldValidationTypedDict + from codat_platform.models.shared.pushoperationchange import PushOperationChangeTypedDict as PushOperationChangeTypedDict + from codat_platform.models.shared.pushoperationref import PushOperationRefTypedDict as PushOperationRefTypedDict + from codat_platform.models.shared.pushoperationstatus import PushOperationStatus as PushOperationStatus + from codat_platform.models.shared.pushoperation import PushOperationTypedDict as PushOperationTypedDict + from codat_platform.models.shared.pushoperations import PushOperationsTypedDict as PushOperationsTypedDict + from codat_platform.models.shared.pushoptionchoice import PushOptionChoiceTypedDict as PushOptionChoiceTypedDict + from codat_platform.models.shared.pushoptionproperty import PushOptionPropertyTypedDict as PushOptionPropertyTypedDict + from codat_platform.models.shared.pushoptiontype import PushOptionType as PushOptionType + from codat_platform.models.shared.pushoption import PushOptionTypedDict as PushOptionTypedDict + from codat_platform.models.shared.pushvalidationinfo import PushValidationInfoTypedDict as PushValidationInfoTypedDict + from codat_platform.models.shared.readcompletedwebhookpayload import ReadCompletedWebhookPayloadTypedDict as ReadCompletedWebhookPayloadTypedDict + from codat_platform.models.shared.readcompletedwebhook import ReadCompletedWebhookTypedDict as ReadCompletedWebhookTypedDict + from codat_platform.models.shared.schema_datatype import SchemaDataType as SchemaDataType + from codat_platform.models.shared.security import Security as Security + from codat_platform.models.shared.security import SecurityTypedDict as SecurityTypedDict + from codat_platform.models.shared.sourcetype import SourceType as SourceType + from codat_platform.models.shared.status import Status as Status + from codat_platform.models.shared.supplementaldataconfiguration import SupplementalDataConfigurationTypedDict as SupplementalDataConfigurationTypedDict + from codat_platform.models.supplemental_data_source_configuration import SupplementalDataSourceConfigurationTypedDict as SupplementalDataSourceConfigurationTypedDict + from codat_platform.models.shared.supportedfeature import SupportedFeatureTypedDict as SupportedFeatureTypedDict + from codat_platform.models.shared.syncsetting import SyncSettingTypedDict as SyncSettingTypedDict + from codat_platform.models.shared.syncsettings import SyncSettingsTypedDict as SyncSettingsTypedDict + from codat_platform.models.shared.updateconnectionstatus import UpdateConnectionStatusTypedDict as UpdateConnectionStatusTypedDict + from codat_platform.models.validation_item1 import ValidationItem1TypedDict as ValidationItem1TypedDict + from codat_platform.models.shared.validationitem import ValidationItemTypedDict as ValidationItemTypedDict + from codat_platform.models.shared.validationresult import ValidationResultTypedDict as ValidationResultTypedDict + from codat_platform.models.shared.validation import ValidationTypedDict as ValidationTypedDict + from codat_platform.models.shared.webhookconsumerprototype import WebhookConsumerPrototypeTypedDict as WebhookConsumerPrototypeTypedDict + from codat_platform.models.shared.webhookconsumer import WebhookConsumerTypedDict as WebhookConsumerTypedDict + from codat_platform.models.shared.webhookconsumers import WebhookConsumersTypedDict as WebhookConsumersTypedDict + from codat_platform.models.shared.writestatus import WriteStatus as WriteStatus + from codat_platform.models.shared.writetype import WriteType as WriteType + from codat_platform.models.content import Content, ContentTypedDict + from codat_platform.models.validationitem1 import ValidationItem1, ValidationItem1TypedDict -_dynamic_imports: dict[str, str] = { - "APIKeyDetails": ".apikeydetails", - "APIKeyDetailsTypedDict": ".apikeydetails", - "APIKeys": ".apikeys", - "APIKeysTypedDict": ".apikeys", - "Branding": ".branding", - "BrandingTypedDict": ".branding", - "BrandingButton": ".brandingbutton", - "BrandingButtonTypedDict": ".brandingbutton", - "BrandingImage": ".brandingimage", - "BrandingImageTypedDict": ".brandingimage", - "BrandingLogo": ".brandinglogo", - "BrandingLogoTypedDict": ".brandinglogo", - "ClientRateLimitWebhook": ".clientratelimitwebhook", - "ClientRateLimitWebhookTypedDict": ".clientratelimitwebhook", - "ClientRateLimitWebhookPayload": ".clientratelimitwebhookpayload", - "ClientRateLimitWebhookPayloadTypedDict": ".clientratelimitwebhookpayload", - "Companies": ".companies", - "CompaniesTypedDict": ".companies", - "Company": ".company", - "CompanyTypedDict": ".company", - "CompanyAccessToken": ".companyaccesstoken", - "CompanyAccessTokenTypedDict": ".companyaccesstoken", - "CompanyDetails": ".companydetails", - "CompanyDetailsTypedDict": ".companydetails", - "CompanyReference": ".companyreference", - "CompanyReferenceLinks": ".companyreference", - "CompanyReferenceLinksTypedDict": ".companyreference", - "CompanyReferenceTypedDict": ".companyreference", - "CompanyRequestBody": ".companyrequestbody", - "CompanyRequestBodyTypedDict": ".companyrequestbody", - "CompanySyncSettings": ".companysyncsettings", - "CompanySyncSettingsTypedDict": ".companysyncsettings", - "CompanyUpdateRequest": ".companyupdaterequest", - "CompanyUpdateRequestTypedDict": ".companyupdaterequest", - "CompanyWebhook": ".companywebhook", - "CompanyWebhookTypedDict": ".companywebhook", - "Connection": ".connection", - "ConnectionTypedDict": ".connection", - "ConnectionManagementAccessToken": ".connectionmanagementaccesstoken", - "ConnectionManagementAccessTokenTypedDict": ".connectionmanagementaccesstoken", - "ConnectionManagementAllowedOrigins": ".connectionmanagementallowedorigins", - "ConnectionManagementAllowedOriginsTypedDict": ".connectionmanagementallowedorigins", - "Connections": ".connections", - "ConnectionsTypedDict": ".connections", - "ConnectionWebhook": ".connectionwebhook", - "ConnectionWebhookTypedDict": ".connectionwebhook", - "ConnectionWebhookPayload": ".connectionwebhookpayload", - "ConnectionWebhookPayloadTypedDict": ".connectionwebhookpayload", - "CreateAPIKey": ".createapikey", - "CreateAPIKeyTypedDict": ".createapikey", - "CustomDataTypeConfiguration": ".customdatatypeconfiguration", - "CustomDataTypeConfigurationTypedDict": ".customdatatypeconfiguration", - "Content": ".customdatatyperecord", - "ContentTypedDict": ".customdatatyperecord", - "CustomDataTypeRecord": ".customdatatyperecord", - "CustomDataTypeRecordTypedDict": ".customdatatyperecord", - "ModifiedDate": ".customdatatyperecord", - "ModifiedDateTypedDict": ".customdatatyperecord", - "CustomDataTypeRecords": ".customdatatyperecords", - "CustomDataTypeRecordsTypedDict": ".customdatatyperecords", - "DataConnectionError": ".dataconnectionerror", - "DataConnectionErrorTypedDict": ".dataconnectionerror", - "ErrorStatus": ".dataconnectionerror", - "DataConnectionStatus": ".dataconnectionstatus", - "DataStatus": ".datastatus", - "DataStatusTypedDict": ".datastatus", - "DataTypes": ".datastatus", - "DataStatuses": ".datastatuses", - "DataStatusesTypedDict": ".datastatuses", - "DataType": ".datatype", - "DataTypeFeature": ".datatypefeature", - "DataTypeFeatureTypedDict": ".datatypefeature", - "DataTypeReadSummary": ".datatypereadsummary", - "DataTypeReadSummaryTypedDict": ".datatypereadsummary", - "DataTypeWriteWebhook": ".datatypewritewebhook", - "DataTypeWriteWebhookTypedDict": ".datatypewritewebhook", - "DataTypeWriteWebhookPayload": ".datatypewritewebhookpayload", - "DataTypeWriteWebhookPayloadTypedDict": ".datatypewritewebhookpayload", - "DataTypeWriteWebhookRecord": ".datatypewritewebhookrecord", - "DataTypeWriteWebhookRecordTypedDict": ".datatypewritewebhookrecord", - "ErrorMessage": ".errormessage", - "ErrorMessageTypedDict": ".errormessage", - "ErrorValidation": ".errorvalidation", - "ErrorValidationTypedDict": ".errorvalidation", - "ErrorValidationItem": ".errorvalidationitem", - "ErrorValidationItemTypedDict": ".errorvalidationitem", - "FeatureState": ".featurestate", - "FeatureType": ".featuretype", - "HalRef": ".halref", - "HalRefTypedDict": ".halref", - "ImageReference": ".imagereference", - "ImageReferenceTypedDict": ".imagereference", - "Integration": ".integration", - "IntegrationTypedDict": ".integration", - "Integrations": ".integrations", - "IntegrationsTypedDict": ".integrations", - "Issue": ".issue", - "IssueLinks": ".issue", - "IssueLinksTypedDict": ".issue", - "IssueTypedDict": ".issue", - "Links": ".links", - "LinksTypedDict": ".links", - "Profile": ".profile", - "ProfileTypedDict": ".profile", - "DatasetStatus": ".pulloperation", - "PullOperation": ".pulloperation", - "PullOperationTypedDict": ".pulloperation", - "PullOperations": ".pulloperations", - "PullOperationsTypedDict": ".pulloperations", - "PushChangeType": ".pushchangetype", - "PushFieldValidation": ".pushfieldvalidation", - "PushFieldValidationTypedDict": ".pushfieldvalidation", - "PushOperation": ".pushoperation", - "PushOperationTypedDict": ".pushoperation", - "PushOperationChange": ".pushoperationchange", - "PushOperationChangeTypedDict": ".pushoperationchange", - "PushOperationRef": ".pushoperationref", - "PushOperationRefTypedDict": ".pushoperationref", - "PushOperations": ".pushoperations", - "PushOperationsTypedDict": ".pushoperations", - "PushOperationStatus": ".pushoperationstatus", - "PushOption": ".pushoption", - "PushOptionTypedDict": ".pushoption", - "PushOptionChoice": ".pushoptionchoice", - "PushOptionChoiceTypedDict": ".pushoptionchoice", - "PushOptionProperty": ".pushoptionproperty", - "PushOptionPropertyTypedDict": ".pushoptionproperty", - "PushOptionType": ".pushoptiontype", - "PushValidationInfo": ".pushvalidationinfo", - "PushValidationInfoTypedDict": ".pushvalidationinfo", - "ReadCompletedWebhook": ".readcompletedwebhook", - "ReadCompletedWebhookTypedDict": ".readcompletedwebhook", - "ReadCompletedWebhookPayload": ".readcompletedwebhookpayload", - "ReadCompletedWebhookPayloadTypedDict": ".readcompletedwebhookpayload", - "SchemaDataType": ".schema_datatype", - "Security": ".security", - "SecurityTypedDict": ".security", - "SourceType": ".sourcetype", - "Status": ".status", - "SupplementalDataConfiguration": ".supplementaldataconfiguration", - "SupplementalDataConfigurationTypedDict": ".supplementaldataconfiguration", - "SupplementalDataSourceConfiguration": ".supplementaldataconfiguration", - "SupplementalDataSourceConfigurationTypedDict": ".supplementaldataconfiguration", - "SupportedFeature": ".supportedfeature", - "SupportedFeatureTypedDict": ".supportedfeature", - "SyncSetting": ".syncsetting", - "SyncSettingTypedDict": ".syncsetting", - "SyncSettings": ".syncsettings", - "SyncSettingsTypedDict": ".syncsettings", - "UpdateConnectionStatus": ".updateconnectionstatus", - "UpdateConnectionStatusTypedDict": ".updateconnectionstatus", - "Validation": ".validation", - "ValidationTypedDict": ".validation", - "ValidationItem": ".validationitem", - "ValidationItemTypedDict": ".validationitem", - "ValidationItem1": ".validationitem1", - "ValidationItem1TypedDict": ".validationitem1", - "ValidationResult": ".validationresult", - "ValidationResultTypedDict": ".validationresult", - "WebhookConsumer": ".webhookconsumer", - "WebhookConsumerTypedDict": ".webhookconsumer", - "WebhookConsumerPrototype": ".webhookconsumerprototype", - "WebhookConsumerPrototypeTypedDict": ".webhookconsumerprototype", - "WebhookConsumers": ".webhookconsumers", - "WebhookConsumersTypedDict": ".webhookconsumers", - "WriteStatus": ".writestatus", - "WriteType": ".writetype", +_dynamic_imports: dict[str, tuple[str, str]] = { + 'APIKeyDetails': ('codat_platform.models.shared.apikeydetails', 'APIKeyDetails'), + 'ApiKeyDetails': ('codat_platform.models.shared.apikeydetails', 'APIKeyDetails'), + 'APIKeyDetailsTypedDict': ('codat_platform.models.shared.apikeydetails', 'APIKeyDetailsTypedDict'), + 'ApiKeyDetailsTypedDict': ('codat_platform.models.shared.apikeydetails', 'APIKeyDetailsTypedDict'), + 'APIKeys': ('codat_platform.models.shared.apikeys', 'APIKeys'), + 'ApiKeys': ('codat_platform.models.shared.apikeys', 'APIKeys'), + 'APIKeysTypedDict': ('codat_platform.models.shared.apikeys', 'APIKeysTypedDict'), + 'ApiKeysTypedDict': ('codat_platform.models.shared.apikeys', 'APIKeysTypedDict'), + 'AccessToken': ('codat_platform.models.access_token', 'AccessToken'), + 'AccessTokenTypedDict': ('codat_platform.models.access_token', 'AccessTokenTypedDict'), + 'Branding': ('codat_platform.models.shared.branding', 'Branding'), + 'BrandingButton': ('codat_platform.models.shared.brandingbutton', 'BrandingButton'), + 'BrandingButtonTypedDict': ('codat_platform.models.shared.brandingbutton', 'BrandingButtonTypedDict'), + 'BrandingImage': ('codat_platform.models.shared.brandingimage', 'BrandingImage'), + 'BrandingImageTypedDict': ('codat_platform.models.shared.brandingimage', 'BrandingImageTypedDict'), + 'BrandingLogo': ('codat_platform.models.shared.brandinglogo', 'BrandingLogo'), + 'BrandingLogoTypedDict': ('codat_platform.models.shared.brandinglogo', 'BrandingLogoTypedDict'), + 'BrandingTypedDict': ('codat_platform.models.shared.branding', 'BrandingTypedDict'), + 'ClientRateLimitWebhook': ('codat_platform.models.shared.clientratelimitwebhook', 'ClientRateLimitWebhook'), + 'ClientRateLimitWebhookPayload': ('codat_platform.models.shared.clientratelimitwebhookpayload', 'ClientRateLimitWebhookPayload'), + 'ClientRateLimitWebhookPayloadTypedDict': ('codat_platform.models.shared.clientratelimitwebhookpayload', 'ClientRateLimitWebhookPayloadTypedDict'), + 'ClientRateLimitWebhookTypedDict': ('codat_platform.models.shared.clientratelimitwebhook', 'ClientRateLimitWebhookTypedDict'), + 'Companies': ('codat_platform.models.shared.companies', 'Companies'), + 'CompaniesTypedDict': ('codat_platform.models.shared.companies', 'CompaniesTypedDict'), + 'Company': ('codat_platform.models.shared.company', 'Company'), + 'CompanyAccessToken': ('codat_platform.models.shared.companyaccesstoken', 'CompanyAccessToken'), + 'CompanyAccessTokenTypedDict': ('codat_platform.models.shared.companyaccesstoken', 'CompanyAccessTokenTypedDict'), + 'CompanyDetails': ('codat_platform.models.shared.companydetails', 'CompanyDetails'), + 'CompanyDetailsTypedDict': ('codat_platform.models.shared.companydetails', 'CompanyDetailsTypedDict'), + 'CompanyProductWebhook': ('codat_platform.models.company_product_webhook', 'CompanyProductWebhook'), + 'CompanyProductWebhookPayload': ('codat_platform.models.company_product_webhook_payload', 'CompanyProductWebhookPayload'), + 'CompanyProductWebhookPayloadTypedDict': ('codat_platform.models.company_product_webhook_payload', 'CompanyProductWebhookPayloadTypedDict'), + 'CompanyProductWebhookTypedDict': ('codat_platform.models.company_product_webhook', 'CompanyProductWebhookTypedDict'), + 'CompanyReference': ('codat_platform.models.shared.companyreference', 'CompanyReference'), + 'CompanyReferenceLinks': ('codat_platform.models.company_reference_links', 'CompanyReferenceLinks'), + 'CompanyReferenceLinksTypedDict': ('codat_platform.models.company_reference_links', 'CompanyReferenceLinksTypedDict'), + 'CompanyReferenceTypedDict': ('codat_platform.models.shared.companyreference', 'CompanyReferenceTypedDict'), + 'CompanyRequestBody': ('codat_platform.models.shared.companyrequestbody', 'CompanyRequestBody'), + 'CompanyRequestBodyTypedDict': ('codat_platform.models.shared.companyrequestbody', 'CompanyRequestBodyTypedDict'), + 'CompanySyncSettings': ('codat_platform.models.shared.companysyncsettings', 'CompanySyncSettings'), + 'CompanySyncSettingsTypedDict': ('codat_platform.models.shared.companysyncsettings', 'CompanySyncSettingsTypedDict'), + 'CompanyTypedDict': ('codat_platform.models.shared.company', 'CompanyTypedDict'), + 'CompanyUpdateRequest': ('codat_platform.models.shared.companyupdaterequest', 'CompanyUpdateRequest'), + 'CompanyUpdateRequestTypedDict': ('codat_platform.models.shared.companyupdaterequest', 'CompanyUpdateRequestTypedDict'), + 'CompanyWebhook': ('codat_platform.models.shared.companywebhook', 'CompanyWebhook'), + 'CompanyWebhookTypedDict': ('codat_platform.models.shared.companywebhook', 'CompanyWebhookTypedDict'), + 'Connection': ('codat_platform.models.shared.connection', 'Connection'), + 'ConnectionManagementAccessToken': ('codat_platform.models.shared.connectionmanagementaccesstoken', 'ConnectionManagementAccessToken'), + 'ConnectionManagementAccessTokenTypedDict': ('codat_platform.models.shared.connectionmanagementaccesstoken', 'ConnectionManagementAccessTokenTypedDict'), + 'ConnectionManagementAllowedOrigins': ('codat_platform.models.shared.connectionmanagementallowedorigins', 'ConnectionManagementAllowedOrigins'), + 'ConnectionManagementAllowedOriginsTypedDict': ('codat_platform.models.shared.connectionmanagementallowedorigins', 'ConnectionManagementAllowedOriginsTypedDict'), + 'ConnectionTypedDict': ('codat_platform.models.shared.connection', 'ConnectionTypedDict'), + 'ConnectionWebhook': ('codat_platform.models.shared.connectionwebhook', 'ConnectionWebhook'), + 'ConnectionWebhookPayload': ('codat_platform.models.shared.connectionwebhookpayload', 'ConnectionWebhookPayload'), + 'ConnectionWebhookPayloadTypedDict': ('codat_platform.models.shared.connectionwebhookpayload', 'ConnectionWebhookPayloadTypedDict'), + 'ConnectionWebhookTypedDict': ('codat_platform.models.shared.connectionwebhook', 'ConnectionWebhookTypedDict'), + 'Connections': ('codat_platform.models.shared.connections', 'Connections'), + 'ConnectionsTypedDict': ('codat_platform.models.shared.connections', 'ConnectionsTypedDict'), + 'Content': ('codat_platform.models.content', 'Content'), + 'ContentTypedDict': ('codat_platform.models.content', 'ContentTypedDict'), + 'CreateAPIKey': ('codat_platform.models.shared.createapikey', 'CreateAPIKey'), + 'CreateApiKey': ('codat_platform.models.shared.createapikey', 'CreateAPIKey'), + 'CreateAPIKeyTypedDict': ('codat_platform.models.shared.createapikey', 'CreateAPIKeyTypedDict'), + 'CreateApiKeyTypedDict': ('codat_platform.models.shared.createapikey', 'CreateAPIKeyTypedDict'), + 'CreateConnectionRequest': ('codat_platform.models.create_connection_request', 'CreateConnectionRequest'), + 'CreateConnectionRequestTypedDict': ('codat_platform.models.create_connection_request', 'CreateConnectionRequestTypedDict'), + 'CurrentStatus': ('codat_platform.models.current_status', 'CurrentStatus'), + 'CustomDataTypeConfiguration': ('codat_platform.models.shared.customdatatypeconfiguration', 'CustomDataTypeConfiguration'), + 'CustomDataTypeConfigurationTypedDict': ('codat_platform.models.shared.customdatatypeconfiguration', 'CustomDataTypeConfigurationTypedDict'), + 'CustomDataTypeRecord': ('codat_platform.models.shared.customdatatyperecord', 'CustomDataTypeRecord'), + 'CustomDataTypeRecordTypedDict': ('codat_platform.models.shared.customdatatyperecord', 'CustomDataTypeRecordTypedDict'), + 'CustomDataTypeRecords': ('codat_platform.models.shared.customdatatyperecords', 'CustomDataTypeRecords'), + 'CustomDataTypeRecordsTypedDict': ('codat_platform.models.shared.customdatatyperecords', 'CustomDataTypeRecordsTypedDict'), + 'DataConnectionError': ('codat_platform.models.shared.dataconnectionerror', 'DataConnectionError'), + 'DataConnectionErrorTypedDict': ('codat_platform.models.shared.dataconnectionerror', 'DataConnectionErrorTypedDict'), + 'DataConnectionStatus': ('codat_platform.models.shared.dataconnectionstatus', 'DataConnectionStatus'), + 'DataStatus': ('codat_platform.models.shared.datastatus', 'DataStatus'), + 'DataStatusTypedDict': ('codat_platform.models.shared.datastatus', 'DataStatusTypedDict'), + 'DataStatuses': ('codat_platform.models.shared.datastatuses', 'DataStatuses'), + 'DataStatusesTypedDict': ('codat_platform.models.shared.datastatuses', 'DataStatusesTypedDict'), + 'DataType': ('codat_platform.models.shared.datatype', 'DataType'), + 'DataTypeFeature': ('codat_platform.models.shared.datatypefeature', 'DataTypeFeature'), + 'DataTypeFeatureTypedDict': ('codat_platform.models.shared.datatypefeature', 'DataTypeFeatureTypedDict'), + 'DataTypeReadSummary': ('codat_platform.models.shared.datatypereadsummary', 'DataTypeReadSummary'), + 'DataTypeReadSummaryTypedDict': ('codat_platform.models.shared.datatypereadsummary', 'DataTypeReadSummaryTypedDict'), + 'DataTypeWriteWebhook': ('codat_platform.models.shared.datatypewritewebhook', 'DataTypeWriteWebhook'), + 'DataTypeWriteWebhookPayload': ('codat_platform.models.shared.datatypewritewebhookpayload', 'DataTypeWriteWebhookPayload'), + 'DataTypeWriteWebhookPayloadTypedDict': ('codat_platform.models.shared.datatypewritewebhookpayload', 'DataTypeWriteWebhookPayloadTypedDict'), + 'DataTypeWriteWebhookRecord': ('codat_platform.models.shared.datatypewritewebhookrecord', 'DataTypeWriteWebhookRecord'), + 'DataTypeWriteWebhookRecordTypedDict': ('codat_platform.models.shared.datatypewritewebhookrecord', 'DataTypeWriteWebhookRecordTypedDict'), + 'DataTypeWriteWebhookTypedDict': ('codat_platform.models.shared.datatypewritewebhook', 'DataTypeWriteWebhookTypedDict'), + 'DataTypes': ('codat_platform.models.data_types', 'DataTypes'), + 'DatasetStatus': ('codat_platform.models.dataset_status', 'DatasetStatus'), + 'ErrorMessage': ('codat_platform.models.shared.errormessage', 'ErrorMessage'), + 'ErrorMessageTypedDict': ('codat_platform.models.shared.errormessage', 'ErrorMessageTypedDict'), + 'ErrorStatus': ('codat_platform.models.error_status', 'ErrorStatus'), + 'ErrorValidation': ('codat_platform.models.shared.errorvalidation', 'ErrorValidation'), + 'ErrorValidationItem': ('codat_platform.models.shared.errorvalidationitem', 'ErrorValidationItem'), + 'ErrorValidationItemTypedDict': ('codat_platform.models.shared.errorvalidationitem', 'ErrorValidationItemTypedDict'), + 'ErrorValidationTypedDict': ('codat_platform.models.shared.errorvalidation', 'ErrorValidationTypedDict'), + 'FeatureState': ('codat_platform.models.shared.featurestate', 'FeatureState'), + 'FeatureType': ('codat_platform.models.shared.featuretype', 'FeatureType'), + 'HalRef': ('codat_platform.models.shared.halref', 'HalRef'), + 'HalRefTypedDict': ('codat_platform.models.shared.halref', 'HalRefTypedDict'), + 'ImageReference': ('codat_platform.models.shared.imagereference', 'ImageReference'), + 'ImageReferenceTypedDict': ('codat_platform.models.shared.imagereference', 'ImageReferenceTypedDict'), + 'Integration': ('codat_platform.models.shared.integration', 'Integration'), + 'IntegrationTypedDict': ('codat_platform.models.shared.integration', 'IntegrationTypedDict'), + 'Integrations': ('codat_platform.models.shared.integrations', 'Integrations'), + 'IntegrationsTypedDict': ('codat_platform.models.shared.integrations', 'IntegrationsTypedDict'), + 'Issue': ('codat_platform.models.shared.issue', 'Issue'), + 'IssueLinks': ('codat_platform.models.issue_links', 'IssueLinks'), + 'IssueLinksTypedDict': ('codat_platform.models.issue_links', 'IssueLinksTypedDict'), + 'IssueTypedDict': ('codat_platform.models.shared.issue', 'IssueTypedDict'), + 'Links': ('codat_platform.models.shared.links', 'Links'), + 'LinksTypedDict': ('codat_platform.models.shared.links', 'LinksTypedDict'), + 'ModifiedDate': ('codat_platform.models.modified_date', 'ModifiedDate'), + 'ModifiedDateTypedDict': ('codat_platform.models.modified_date', 'ModifiedDateTypedDict'), + 'PagingInfo': ('codat_platform.models.paging_info', 'PagingInfo'), + 'PagingInfoTypedDict': ('codat_platform.models.paging_info', 'PagingInfoTypedDict'), + 'Profile': ('codat_platform.models.shared.profile', 'Profile'), + 'ProfileTypedDict': ('codat_platform.models.shared.profile', 'ProfileTypedDict'), + 'PullOperation': ('codat_platform.models.shared.pulloperation', 'PullOperation'), + 'PullOperationTypedDict': ('codat_platform.models.shared.pulloperation', 'PullOperationTypedDict'), + 'PullOperations': ('codat_platform.models.shared.pulloperations', 'PullOperations'), + 'PullOperationsTypedDict': ('codat_platform.models.shared.pulloperations', 'PullOperationsTypedDict'), + 'PushChangeType': ('codat_platform.models.shared.pushchangetype', 'PushChangeType'), + 'PushFieldValidation': ('codat_platform.models.shared.pushfieldvalidation', 'PushFieldValidation'), + 'PushFieldValidationTypedDict': ('codat_platform.models.shared.pushfieldvalidation', 'PushFieldValidationTypedDict'), + 'PushOperation': ('codat_platform.models.shared.pushoperation', 'PushOperation'), + 'PushOperationChange': ('codat_platform.models.shared.pushoperationchange', 'PushOperationChange'), + 'PushOperationChangeTypedDict': ('codat_platform.models.shared.pushoperationchange', 'PushOperationChangeTypedDict'), + 'PushOperationRef': ('codat_platform.models.shared.pushoperationref', 'PushOperationRef'), + 'PushOperationRefTypedDict': ('codat_platform.models.shared.pushoperationref', 'PushOperationRefTypedDict'), + 'PushOperationStatus': ('codat_platform.models.shared.pushoperationstatus', 'PushOperationStatus'), + 'PushOperationTypedDict': ('codat_platform.models.shared.pushoperation', 'PushOperationTypedDict'), + 'PushOperations': ('codat_platform.models.shared.pushoperations', 'PushOperations'), + 'PushOperationsTypedDict': ('codat_platform.models.shared.pushoperations', 'PushOperationsTypedDict'), + 'PushOption': ('codat_platform.models.shared.pushoption', 'PushOption'), + 'PushOptionChoice': ('codat_platform.models.shared.pushoptionchoice', 'PushOptionChoice'), + 'PushOptionChoiceTypedDict': ('codat_platform.models.shared.pushoptionchoice', 'PushOptionChoiceTypedDict'), + 'PushOptionProperty': ('codat_platform.models.shared.pushoptionproperty', 'PushOptionProperty'), + 'PushOptionPropertyTypedDict': ('codat_platform.models.shared.pushoptionproperty', 'PushOptionPropertyTypedDict'), + 'PushOptionType': ('codat_platform.models.shared.pushoptiontype', 'PushOptionType'), + 'PushOptionTypedDict': ('codat_platform.models.shared.pushoption', 'PushOptionTypedDict'), + 'PushValidationInfo': ('codat_platform.models.shared.pushvalidationinfo', 'PushValidationInfo'), + 'PushValidationInfoTypedDict': ('codat_platform.models.shared.pushvalidationinfo', 'PushValidationInfoTypedDict'), + 'ReadCompletedWebhook': ('codat_platform.models.shared.readcompletedwebhook', 'ReadCompletedWebhook'), + 'ReadCompletedWebhookPayload': ('codat_platform.models.shared.readcompletedwebhookpayload', 'ReadCompletedWebhookPayload'), + 'ReadCompletedWebhookPayloadTypedDict': ('codat_platform.models.shared.readcompletedwebhookpayload', 'ReadCompletedWebhookPayloadTypedDict'), + 'ReadCompletedWebhookTypedDict': ('codat_platform.models.shared.readcompletedwebhook', 'ReadCompletedWebhookTypedDict'), + 'RefreshProductDataRequest': ('codat_platform.models.refresh_product_data_request', 'RefreshProductDataRequest'), + 'RefreshProductDataRequestTypedDict': ('codat_platform.models.refresh_product_data_request', 'RefreshProductDataRequestTypedDict'), + 'SchemaDataType': ('codat_platform.models.shared.schema_datatype', 'SchemaDataType'), + 'Security': ('codat_platform.models.shared.security', 'Security'), + 'SecurityTypedDict': ('codat_platform.models.shared.security', 'SecurityTypedDict'), + 'SetCompanySyncSettingsRequest': ('codat_platform.models.set_company_sync_settings_request', 'SetCompanySyncSettingsRequest'), + 'SetCompanySyncSettingsRequestTypedDict': ('codat_platform.models.set_company_sync_settings_request', 'SetCompanySyncSettingsRequestTypedDict'), + 'SourceType': ('codat_platform.models.shared.sourcetype', 'SourceType'), + 'Status': ('codat_platform.models.shared.status', 'Status'), + 'SupplementalDataConfiguration': ('codat_platform.models.shared.supplementaldataconfiguration', 'SupplementalDataConfiguration'), + 'SupplementalDataConfigurationTypedDict': ('codat_platform.models.shared.supplementaldataconfiguration', 'SupplementalDataConfigurationTypedDict'), + 'SupplementalDataSourceConfiguration': ('codat_platform.models.supplemental_data_source_configuration', 'SupplementalDataSourceConfiguration'), + 'SupplementalDataSourceConfigurationTypedDict': ('codat_platform.models.supplemental_data_source_configuration', 'SupplementalDataSourceConfigurationTypedDict'), + 'SupportedFeature': ('codat_platform.models.shared.supportedfeature', 'SupportedFeature'), + 'SupportedFeatureTypedDict': ('codat_platform.models.shared.supportedfeature', 'SupportedFeatureTypedDict'), + 'SyncSetting': ('codat_platform.models.shared.syncsetting', 'SyncSetting'), + 'SyncSettingTypedDict': ('codat_platform.models.shared.syncsetting', 'SyncSettingTypedDict'), + 'SyncSettings': ('codat_platform.models.shared.syncsettings', 'SyncSettings'), + 'SyncSettingsTypedDict': ('codat_platform.models.shared.syncsettings', 'SyncSettingsTypedDict'), + 'UpdateConnectionStatus': ('codat_platform.models.shared.updateconnectionstatus', 'UpdateConnectionStatus'), + 'UpdateConnectionStatusTypedDict': ('codat_platform.models.shared.updateconnectionstatus', 'UpdateConnectionStatusTypedDict'), + 'UpdateProfileSyncSettingsRequest': ('codat_platform.models.update_profile_sync_settings_request', 'UpdateProfileSyncSettingsRequest'), + 'UpdateProfileSyncSettingsRequestTypedDict': ('codat_platform.models.update_profile_sync_settings_request', 'UpdateProfileSyncSettingsRequestTypedDict'), + 'Validation': ('codat_platform.models.shared.validation', 'Validation'), + 'ValidationItem': ('codat_platform.models.shared.validationitem', 'ValidationItem'), + 'ValidationItem1': ('codat_platform.models.validationitem1', 'ValidationItem1'), + 'ValidationItem1TypedDict': ('codat_platform.models.validationitem1', 'ValidationItem1TypedDict'), + 'ValidationItemTypedDict': ('codat_platform.models.shared.validationitem', 'ValidationItemTypedDict'), + 'ValidationResult': ('codat_platform.models.shared.validationresult', 'ValidationResult'), + 'ValidationResultTypedDict': ('codat_platform.models.shared.validationresult', 'ValidationResultTypedDict'), + 'ValidationTypedDict': ('codat_platform.models.shared.validation', 'ValidationTypedDict'), + 'WebhookConsumer': ('codat_platform.models.shared.webhookconsumer', 'WebhookConsumer'), + 'WebhookConsumerPrototype': ('codat_platform.models.shared.webhookconsumerprototype', 'WebhookConsumerPrototype'), + 'WebhookConsumerPrototypeTypedDict': ('codat_platform.models.shared.webhookconsumerprototype', 'WebhookConsumerPrototypeTypedDict'), + 'WebhookConsumerTypedDict': ('codat_platform.models.shared.webhookconsumer', 'WebhookConsumerTypedDict'), + 'WebhookConsumers': ('codat_platform.models.shared.webhookconsumers', 'WebhookConsumers'), + 'WebhookConsumersTypedDict': ('codat_platform.models.shared.webhookconsumers', 'WebhookConsumersTypedDict'), + 'WebhookZapierKey': ('codat_platform.models.webhook_zapier_key', 'WebhookZapierKey'), + 'WebhookZapierKeyTypedDict': ('codat_platform.models.webhook_zapier_key', 'WebhookZapierKeyTypedDict'), + 'WriteStatus': ('codat_platform.models.shared.writestatus', 'WriteStatus'), + 'WriteType': ('codat_platform.models.shared.writetype', 'WriteType'), } -def __getattr__(attr_name: str) -> Any: - return lazy_getattr( - attr_name, package=__package__, dynamic_imports=_dynamic_imports - ) +def __getattr__(attr_name): + try: + module_path, source_name = _dynamic_imports[attr_name] + except KeyError: + raise AttributeError( + f"module {__name__!r} has no attribute {attr_name!r}" + ) from None + module = import_module(module_path, __package__) + return getattr(module, source_name) def __dir__(): - return lazy_dir(dynamic_imports=_dynamic_imports) + return sorted(set(globals()) | set(_dynamic_imports)) diff --git a/platform/src/codat_platform/models/shared/apikeydetails.py b/platform/src/codat_platform/models/shared/apikeydetails.py index 6cb802ad6..55a3bbc63 100644 --- a/platform/src/codat_platform/models/shared/apikeydetails.py +++ b/platform/src/codat_platform/models/shared/apikeydetails.py @@ -1,112 +1,119 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from typing import Optional, Set +from typing_extensions import Self -class APIKeyDetailsTypedDict(TypedDict): - r"""Details of the API key.""" +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL +class APIKeyDetails(BaseModel): - api_key: NotRequired[str] - r"""The API key value used to make authenticated http requests.""" - created_date: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'name'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + Details of the API key. + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier for the API key.") + name: OptionalNullable[str] = Field(default=UNSET, description="A meaningful name assigned to the API key.") + api_key: Optional[str] = Field(default=None, description="The API key value used to make authenticated http requests.", alias="apiKey") + created_date: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="createdDate") + __properties: ClassVar[List[str]] = ["id", "name", "apiKey", "createdDate"] - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of APIKeyDetails from a JSON string""" + return cls.from_dict(json.loads(json_str)) - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - id: NotRequired[str] - r"""Unique identifier for the API key.""" - name: NotRequired[Nullable[str]] - r"""A meaningful name assigned to the API key.""" + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: -class APIKeyDetails(BaseModel): - r"""Details of the API key.""" + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - api_key: Annotated[Optional[str], pydantic.Field(alias="apiKey")] = None - r"""The API key value used to make authenticated http requests.""" + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - created_date: Annotated[Optional[str], pydantic.Field(alias="createdDate")] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of APIKeyDetails from a dict""" + if obj is None: + return None - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + if not isinstance(obj, dict): + return cls.model_validate(obj) + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "apiKey": obj.get("apiKey"), + "createdDate": obj.get("createdDate") + }) + return _obj - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - id: Optional[str] = None - r"""Unique identifier for the API key.""" +class APIKeyDetailsTypedDict(TypedDict): + """TypedDict variant of APIKeyDetails, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + api_key: NotRequired[Optional[str]] + created_date: NotRequired[Optional[str]] - name: OptionalNullable[str] = UNSET - r"""A meaningful name assigned to the API key.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["apiKey", "createdDate", "id", "name"]) - nullable_fields = set(["name"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - APIKeyDetails.model_rebuild() -except NameError: - pass +# POC spelling of APIKeyDetails, kept as an alias so existing imports keep working. +ApiKeyDetails = APIKeyDetails +ApiKeyDetailsTypedDict = APIKeyDetailsTypedDict diff --git a/platform/src/codat_platform/models/shared/apikeys.py b/platform/src/codat_platform/models/shared/apikeys.py index b1f65cd54..0e9ff0659 100644 --- a/platform/src/codat_platform/models/shared/apikeys.py +++ b/platform/src/codat_platform/models/shared/apikeys.py @@ -1,32 +1,113 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .apikeydetails import APIKeyDetails, APIKeyDetailsTypedDict -from codat_platform.types import BaseModel, Nullable, UNSET_SENTINEL -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class APIKeysTypedDict(TypedDict): - results: NotRequired[List[Nullable[APIKeyDetailsTypedDict]]] + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.apikeydetails import APIKeyDetails, APIKeyDetailsTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_platform.types import Nullable class APIKeys(BaseModel): - results: Optional[List[Nullable[APIKeyDetails]]] = None @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["results"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + APIKeys + """ # noqa: E501 + results: Optional[List[Nullable[APIKeyDetails]]] = None + __properties: ClassVar[List[str]] = ["results"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of APIKeys from a JSON string""" + return cls.from_dict(json.loads(json_str)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of APIKeys from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "results": [APIKeyDetails.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj + + + + + +class APIKeysTypedDict(TypedDict): + """TypedDict variant of APIKeys, for dict-literal request/response inputs.""" + results: NotRequired[Optional[List[Nullable[APIKeyDetailsTypedDict]]]] - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m +# POC spelling of APIKeys, kept as an alias so existing imports keep working. +ApiKeys = APIKeys +ApiKeysTypedDict = APIKeysTypedDict diff --git a/platform/src/codat_platform/models/shared/branding.py b/platform/src/codat_platform/models/shared/branding.py index 6b93d19c4..70c6a3bca 100644 --- a/platform/src/codat_platform/models/shared/branding.py +++ b/platform/src/codat_platform/models/shared/branding.py @@ -1,52 +1,113 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .brandingbutton import BrandingButton, BrandingButtonTypedDict -from .brandinglogo import BrandingLogo, BrandingLogoTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class BrandingTypedDict(TypedDict): - button: NotRequired[BrandingButtonTypedDict] - r"""Button branding references.""" - logo: NotRequired[BrandingLogoTypedDict] - r"""Logo branding references.""" - source_id: NotRequired[str] - r"""A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class Branding(BaseModel): - button: Optional[BrandingButton] = None - r"""Button branding references.""" - logo: Optional[BrandingLogo] = None - r"""Logo branding references.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - source_id: Annotated[Optional[str], pydantic.Field(alias="sourceId")] = None - r"""A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.brandingbutton import BrandingButton, BrandingButtonTypedDict +from codat_platform.models.shared.brandinglogo import BrandingLogo, BrandingLogoTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class Branding(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["button", "logo", "sourceId"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Branding + """ # noqa: E501 + logo: Optional[BrandingLogo] = None + button: Optional[BrandingButton] = None + source_id: Optional[str] = Field(default=None, description="A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`.", alias="sourceId") + __properties: ClassVar[List[str]] = ["logo", "button", "sourceId"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - return m + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Branding from a JSON string""" + return cls.from_dict(json.loads(json_str)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. -try: - Branding.model_rebuild() -except NameError: - pass + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of logo + if self.logo: + _dict['logo'] = self.logo.to_dict() + # override the default output from pydantic by calling `to_dict()` of button + if self.button: + _dict['button'] = self.button.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Branding from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "logo": BrandingLogo.from_dict(obj["logo"]) if obj.get("logo") is not None else None, + "button": BrandingButton.from_dict(obj["button"]) if obj.get("button") is not None else None, + "sourceId": obj.get("sourceId") + }) + return _obj + + + + + +class BrandingTypedDict(TypedDict): + """TypedDict variant of Branding, for dict-literal request/response inputs.""" + logo: NotRequired[Optional[BrandingLogoTypedDict]] + button: NotRequired[Optional[BrandingButtonTypedDict]] + source_id: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/shared/brandingbutton.py b/platform/src/codat_platform/models/shared/brandingbutton.py index 99ccfdc71..f2a2b1580 100644 --- a/platform/src/codat_platform/models/shared/brandingbutton.py +++ b/platform/src/codat_platform/models/shared/brandingbutton.py @@ -1,39 +1,109 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .brandingimage import BrandingImage, BrandingImageTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class BrandingButtonTypedDict(TypedDict): - r"""Button branding references.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - default: NotRequired[BrandingImageTypedDict] - hover: NotRequired[BrandingImageTypedDict] + Do not edit the class manually. +""" # noqa: E501 -class BrandingButton(BaseModel): - r"""Button branding references.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - default: Optional[BrandingImage] = None +from pydantic import BaseModel, ConfigDict, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.brandingimage import BrandingImage, BrandingImageTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - hover: Optional[BrandingImage] = None +class BrandingButton(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["default", "hover"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Button branding references. + """ # noqa: E501 + default: Optional[BrandingImage] = None + hover: Optional[BrandingImage] = None + __properties: ClassVar[List[str]] = ["default", "hover"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BrandingButton from a JSON string""" + return cls.from_dict(json.loads(json_str)) - return m + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of default + if self.default: + _dict['default'] = self.default.to_dict() + # override the default output from pydantic by calling `to_dict()` of hover + if self.hover: + _dict['hover'] = self.hover.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BrandingButton from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "default": BrandingImage.from_dict(obj["default"]) if obj.get("default") is not None else None, + "hover": BrandingImage.from_dict(obj["hover"]) if obj.get("hover") is not None else None + }) + return _obj + + + + + +class BrandingButtonTypedDict(TypedDict): + """TypedDict variant of BrandingButton, for dict-literal request/response inputs.""" + default: NotRequired[Optional[BrandingImageTypedDict]] + hover: NotRequired[Optional[BrandingImageTypedDict]] diff --git a/platform/src/codat_platform/models/shared/brandingimage.py b/platform/src/codat_platform/models/shared/brandingimage.py index eefb28e6b..9f1ee1108 100644 --- a/platform/src/codat_platform/models/shared/brandingimage.py +++ b/platform/src/codat_platform/models/shared/brandingimage.py @@ -1,34 +1,103 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .imagereference import ImageReference, ImageReferenceTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class BrandingImageTypedDict(TypedDict): - image: NotRequired[ImageReferenceTypedDict] - r"""Image reference.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.imagereference import ImageReference, ImageReferenceTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class BrandingImage(BaseModel): - image: Optional[ImageReference] = None - r"""Image reference.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["image"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + BrandingImage + """ # noqa: E501 + image: Optional[ImageReference] = None + __properties: ClassVar[List[str]] = ["image"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BrandingImage from a JSON string""" + return cls.from_dict(json.loads(json_str)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - return m + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of image + if self.image: + _dict['image'] = self.image.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BrandingImage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "image": ImageReference.from_dict(obj["image"]) if obj.get("image") is not None else None + }) + return _obj + + + + + +class BrandingImageTypedDict(TypedDict): + """TypedDict variant of BrandingImage, for dict-literal request/response inputs.""" + image: NotRequired[Optional[ImageReferenceTypedDict]] diff --git a/platform/src/codat_platform/models/shared/brandinglogo.py b/platform/src/codat_platform/models/shared/brandinglogo.py index 4f98e8775..0ff0ebfcf 100644 --- a/platform/src/codat_platform/models/shared/brandinglogo.py +++ b/platform/src/codat_platform/models/shared/brandinglogo.py @@ -1,39 +1,109 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .brandingimage import BrandingImage, BrandingImageTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class BrandingLogoTypedDict(TypedDict): - r"""Logo branding references.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - full: NotRequired[BrandingImageTypedDict] - square: NotRequired[BrandingImageTypedDict] + Do not edit the class manually. +""" # noqa: E501 -class BrandingLogo(BaseModel): - r"""Logo branding references.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - full: Optional[BrandingImage] = None +from pydantic import BaseModel, ConfigDict, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.brandingimage import BrandingImage, BrandingImageTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - square: Optional[BrandingImage] = None +class BrandingLogo(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["full", "square"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Logo branding references. + """ # noqa: E501 + full: Optional[BrandingImage] = None + square: Optional[BrandingImage] = None + __properties: ClassVar[List[str]] = ["full", "square"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BrandingLogo from a JSON string""" + return cls.from_dict(json.loads(json_str)) - return m + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of full + if self.full: + _dict['full'] = self.full.to_dict() + # override the default output from pydantic by calling `to_dict()` of square + if self.square: + _dict['square'] = self.square.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BrandingLogo from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "full": BrandingImage.from_dict(obj["full"]) if obj.get("full") is not None else None, + "square": BrandingImage.from_dict(obj["square"]) if obj.get("square") is not None else None + }) + return _obj + + + + + +class BrandingLogoTypedDict(TypedDict): + """TypedDict variant of BrandingLogo, for dict-literal request/response inputs.""" + full: NotRequired[Optional[BrandingImageTypedDict]] + square: NotRequired[Optional[BrandingImageTypedDict]] diff --git a/platform/src/codat_platform/models/shared/clientratelimitwebhook.py b/platform/src/codat_platform/models/shared/clientratelimitwebhook.py index 61ed5cac9..038d774f1 100644 --- a/platform/src/codat_platform/models/shared/clientratelimitwebhook.py +++ b/platform/src/codat_platform/models/shared/clientratelimitwebhook.py @@ -1,97 +1,112 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .clientratelimitwebhookpayload import ( - ClientRateLimitWebhookPayload, - ClientRateLimitWebhookPayloadTypedDict, -) -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ClientRateLimitWebhookTypedDict(TypedDict): - event_type: NotRequired[str] - r"""The type of event.""" - generated_date: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayload, ClientRateLimitWebhookPayloadTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` +class ClientRateLimitWebhook(BaseModel): - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} """ - id: NotRequired[str] - r"""Unique identifier of the event.""" - payload: NotRequired[ClientRateLimitWebhookPayloadTypedDict] + ClientRateLimitWebhook + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the event.") + event_type: Optional[str] = Field(default=None, description="The type of event.", alias="eventType") + generated_date: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="generatedDate") + payload: Optional[ClientRateLimitWebhookPayload] = None + __properties: ClassVar[List[str]] = ["id", "eventType", "generatedDate", "payload"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class ClientRateLimitWebhook(BaseModel): - event_type: Annotated[Optional[str], pydantic.Field(alias="eventType")] = None - r"""The type of event.""" - generated_date: Annotated[Optional[str], pydantic.Field(alias="generatedDate")] = ( - None - ) - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ClientRateLimitWebhook from a JSON string""" + return cls.from_dict(json.loads(json_str)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of payload + if self.payload: + _dict['payload'] = self.payload.to_dict() + return _dict - id: Optional[str] = None - r"""Unique identifier of the event.""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ClientRateLimitWebhook from a dict""" + if obj is None: + return None - payload: Optional[ClientRateLimitWebhookPayload] = None + if not isinstance(obj, dict): + return cls.model_validate(obj) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["eventType", "generatedDate", "id", "payload"]) - serialized = handler(self) - m = {} + _obj = cls.model_validate({ + "id": obj.get("id"), + "eventType": obj.get("eventType"), + "generatedDate": obj.get("generatedDate"), + "payload": ClientRateLimitWebhookPayload.from_dict(obj["payload"]) if obj.get("payload") is not None else None + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - ClientRateLimitWebhook.model_rebuild() -except NameError: - pass +class ClientRateLimitWebhookTypedDict(TypedDict): + """TypedDict variant of ClientRateLimitWebhook, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + event_type: NotRequired[Optional[str]] + generated_date: NotRequired[Optional[str]] + payload: NotRequired[Optional[ClientRateLimitWebhookPayloadTypedDict]] diff --git a/platform/src/codat_platform/models/shared/clientratelimitwebhookpayload.py b/platform/src/codat_platform/models/shared/clientratelimitwebhookpayload.py index ae4fad44e..ffa814c64 100644 --- a/platform/src/codat_platform/models/shared/clientratelimitwebhookpayload.py +++ b/platform/src/codat_platform/models/shared/clientratelimitwebhookpayload.py @@ -1,90 +1,105 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ClientRateLimitWebhookPayloadTypedDict(TypedDict): - daily_quota: NotRequired[int] - r"""The number of available requests per day.""" - expiry_date: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` +class ClientRateLimitWebhookPayload(BaseModel): - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} """ - quota_remaining: NotRequired[int] - r"""Total number of requests remaining for your client.""" + ClientRateLimitWebhookPayload + """ # noqa: E501 + daily_quota: Optional[int] = Field(default=None, description="The number of available requests per day.", alias="dailyQuota") + quota_remaining: Optional[int] = Field(default=None, description="Total number of requests remaining for your client.", alias="quotaRemaining") + expiry_date: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="expiryDate") + __properties: ClassVar[List[str]] = ["dailyQuota", "quotaRemaining", "expiryDate"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class ClientRateLimitWebhookPayload(BaseModel): - daily_quota: Annotated[Optional[int], pydantic.Field(alias="dailyQuota")] = None - r"""The number of available requests per day.""" - expiry_date: Annotated[Optional[str], pydantic.Field(alias="expiryDate")] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ClientRateLimitWebhookPayload from a JSON string""" + return cls.from_dict(json.loads(json_str)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - quota_remaining: Annotated[ - Optional[int], pydantic.Field(alias="quotaRemaining") - ] = None - r"""Total number of requests remaining for your client.""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ClientRateLimitWebhookPayload from a dict""" + if obj is None: + return None - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["dailyQuota", "expiryDate", "quotaRemaining"]) - serialized = handler(self) - m = {} + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "dailyQuota": obj.get("dailyQuota"), + "quotaRemaining": obj.get("quotaRemaining"), + "expiryDate": obj.get("expiryDate") + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - ClientRateLimitWebhookPayload.model_rebuild() -except NameError: - pass +class ClientRateLimitWebhookPayloadTypedDict(TypedDict): + """TypedDict variant of ClientRateLimitWebhookPayload, for dict-literal request/response inputs.""" + daily_quota: NotRequired[Optional[int]] + quota_remaining: NotRequired[Optional[int]] + expiry_date: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/shared/companies.py b/platform/src/codat_platform/models/shared/companies.py index 23a9821dd..64c2a52d3 100644 --- a/platform/src/codat_platform/models/shared/companies.py +++ b/platform/src/codat_platform/models/shared/companies.py @@ -1,58 +1,124 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .company import Company, CompanyTypedDict -from .links import Links, LinksTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.company import Company, CompanyTypedDict +from codat_platform.models.shared.links import Links, LinksTypedDict +from typing import Optional, Set +from typing_extensions import Self +class Companies(BaseModel): -class CompaniesTypedDict(TypedDict): - links: LinksTypedDict - page_number: int - r"""Current page number.""" - page_size: int - r"""Number of items to return in results array.""" - total_results: int - r"""Total number of items.""" - results: NotRequired[List[CompanyTypedDict]] + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + Companies + """ # noqa: E501 + page_number: int = Field(description="Current page number.", alias="pageNumber") + page_size: int = Field(description="Number of items to return in results array.", alias="pageSize") + total_results: int = Field(description="Total number of items.", alias="totalResults") + links: Links = Field(alias="_links") + results: Optional[List[Company]] = None + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links", "results"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class Companies(BaseModel): - links: Annotated[Links, pydantic.Field(alias="_links")] - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Companies from a JSON string""" + return cls.from_dict(json.loads(json_str)) - results: Optional[List[Company]] = None + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["results"]) - serialized = handler(self) - m = {} + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['_links'] = self.links.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + return _dict - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Companies from a dict""" + if obj is None: + return None - return m + if not isinstance(obj, dict): + return cls.model_validate(obj) + _obj = cls.model_validate({ + "pageNumber": obj.get("pageNumber"), + "pageSize": obj.get("pageSize"), + "totalResults": obj.get("totalResults"), + "_links": Links.from_dict(obj["_links"]) if obj.get("_links") is not None else None, + "results": [Company.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj -try: - Companies.model_rebuild() -except NameError: - pass + + + + +class CompaniesTypedDict(TypedDict): + """TypedDict variant of Companies, for dict-literal request/response inputs.""" + page_number: NotRequired[int] + page_size: NotRequired[int] + total_results: NotRequired[int] + links: NotRequired[LinksTypedDict] + results: NotRequired[Optional[List[CompanyTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/company.py b/platform/src/codat_platform/models/shared/company.py index 6337dfaff..7e5b9e273 100644 --- a/platform/src/codat_platform/models/shared/company.py +++ b/platform/src/codat_platform/models/shared/company.py @@ -1,219 +1,157 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .companyreference import CompanyReference, CompanyReferenceTypedDict -from .connection import Connection, ConnectionTypedDict -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Dict, List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class CompanyTypedDict(TypedDict): - r"""In Codat, a company represents a business sharing access to their data. Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources such as one connection to [Xero](https://docs.codat.io/integrations/accounting/xero/accounting-xero) for accounting data, two connections to [Plaid](https://docs.codat.io/integrations/banking/plaid/banking-plaid) for two bank accounts and a connection to [Zettle](https://docs.codat.io/integrations/commerce/zettle/commerce-zettle) for POS data. - - Typically each company is one of your customers. - - When you create a company, you can specify a `name` and we will automatically generate a unique `id` for the company. You can also add a `description` to store any additional information about the company. - """ - - id: str - r"""Unique identifier for your SMB in Codat.""" - name: str - r"""The name of the company""" - redirect: str - r"""The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company.""" - created: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - created_by_user_name: NotRequired[Nullable[str]] - r"""Name of user that created the company in Codat.""" - data_connections: NotRequired[List[ConnectionTypedDict]] - description: NotRequired[str] - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - last_sync: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + Do not edit the class manually. +""" # noqa: E501 - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.companyreference import CompanyReference, CompanyReferenceTypedDict +from codat_platform.models.shared.connection import Connection, ConnectionTypedDict +from typing import Optional, Set +from typing_extensions import Self - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - products: NotRequired[List[str]] - r"""An array of products that are currently enabled for the company.""" - reference_parent_company: NotRequired[CompanyReferenceTypedDict] - reference_subsidiary_companies: NotRequired[List[CompanyReferenceTypedDict]] - r"""A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children.""" - tags: NotRequired[Dict[str, str]] - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" - - +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL class Company(BaseModel): - r"""In Codat, a company represents a business sharing access to their data. Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources such as one connection to [Xero](https://docs.codat.io/integrations/accounting/xero/accounting-xero) for accounting data, two connections to [Plaid](https://docs.codat.io/integrations/banking/plaid/banking-plaid) for two bank accounts and a connection to [Zettle](https://docs.codat.io/integrations/commerce/zettle/commerce-zettle) for POS data. - - Typically each company is one of your customers. - - When you create a company, you can specify a `name` and we will automatically generate a unique `id` for the company. You can also add a `description` to store any additional information about the company. - """ - - id: str - r"""Unique identifier for your SMB in Codat.""" - - name: str - r"""The name of the company""" - redirect: str - r"""The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company.""" - - created: Optional[str] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - - created_by_user_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="createdByUserName") - ] = UNSET - r"""Name of user that created the company in Codat.""" - - data_connections: Annotated[ - Optional[List[Connection]], pydantic.Field(alias="dataConnections") - ] = None - - description: Optional[str] = None - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - - last_sync: Annotated[Optional[str], pydantic.Field(alias="lastSync")] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'createdByUserName', 'created_by_user_name'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ + In Codat, a company represents a business sharing access to their data. Each company can have multiple [connections](https://docs.codat.io/platform-api#/schemas/Connection) to different data sources such as one connection to [Xero](https://docs.codat.io/integrations/accounting/xero/accounting-xero) for accounting data, two connections to [Plaid](https://docs.codat.io/integrations/banking/plaid/banking-plaid) for two bank accounts and a connection to [Zettle](https://docs.codat.io/integrations/commerce/zettle/commerce-zettle) for POS data. Typically each company is one of your customers. When you create a company, you can specify a `name` and we will automatically generate a unique `id` for the company. You can also add a `description` to store any additional information about the company. + """ # noqa: E501 + id: str = Field(description="Unique identifier for your SMB in Codat.") + name: str = Field(description="The name of the company") + description: Optional[str] = Field(default=None, description="A description of the property.") + redirect: str = Field(description="The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company.") + last_sync: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="lastSync") + created: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.") + created_by_user_name: OptionalNullable[str] = Field(default=UNSET, description="Name of user that created the company in Codat.", alias="createdByUserName") + products: Optional[List[str]] = Field(default=None, description="An array of products that are currently enabled for the company.") + tags: Optional[Dict[str, str]] = Field(default=None, description="A collection of user-defined key-value pairs that store custom metadata against the company.") + reference_parent_company: Optional[CompanyReference] = Field(default=None, description="The parent entity or controlling organization of this company. Null if the company has no parent.", alias="referenceParentCompany") + reference_subsidiary_companies: Optional[List[CompanyReference]] = Field(default=None, description="A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children.", alias="referenceSubsidiaryCompanies") + data_connections: Optional[List[Connection]] = Field(default=None, alias="dataConnections") + __properties: ClassVar[List[str]] = ["id", "name", "description", "redirect", "lastSync", "created", "createdByUserName", "products", "tags", "referenceParentCompany", "referenceSubsidiaryCompanies", "dataConnections"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Company from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of reference_parent_company + if self.reference_parent_company: + _dict['referenceParentCompany'] = self.reference_parent_company.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in reference_subsidiary_companies (list) + _items = [] + if self.reference_subsidiary_companies: + for _item_reference_subsidiary_companies in self.reference_subsidiary_companies: + if _item_reference_subsidiary_companies: + _items.append(_item_reference_subsidiary_companies.to_dict()) + _dict['referenceSubsidiaryCompanies'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in data_connections (list) + _items = [] + if self.data_connections: + for _item_data_connections in self.data_connections: + if _item_data_connections: + _items.append(_item_data_connections.to_dict()) + _dict['dataConnections'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Company from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "description": obj.get("description"), + "redirect": obj.get("redirect"), + "lastSync": obj.get("lastSync"), + "created": obj.get("created"), + "createdByUserName": obj.get("createdByUserName"), + "products": obj.get("products"), + "tags": obj.get("tags"), + "referenceParentCompany": CompanyReference.from_dict(obj["referenceParentCompany"]) if obj.get("referenceParentCompany") is not None else None, + "referenceSubsidiaryCompanies": [CompanyReference.from_dict(_item) for _item in obj["referenceSubsidiaryCompanies"]] if obj.get("referenceSubsidiaryCompanies") is not None else None, + "dataConnections": [Connection.from_dict(_item) for _item in obj["dataConnections"]] if obj.get("dataConnections") is not None else None + }) + return _obj - products: Optional[List[str]] = None - r"""An array of products that are currently enabled for the company.""" - reference_parent_company: Annotated[ - Optional[CompanyReference], pydantic.Field(alias="referenceParentCompany") - ] = None - reference_subsidiary_companies: Annotated[ - Optional[List[CompanyReference]], - pydantic.Field(alias="referenceSubsidiaryCompanies"), - ] = None - r"""A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children.""" - tags: Optional[Dict[str, str]] = None - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "created", - "createdByUserName", - "dataConnections", - "description", - "lastSync", - "products", - "referenceParentCompany", - "referenceSubsidiaryCompanies", - "tags", - ] - ) - nullable_fields = set(["createdByUserName"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - Company.model_rebuild() -except NameError: - pass +class CompanyTypedDict(TypedDict): + """TypedDict variant of Company, for dict-literal request/response inputs.""" + id: NotRequired[str] + name: NotRequired[str] + description: NotRequired[Optional[str]] + redirect: NotRequired[str] + last_sync: NotRequired[Optional[str]] + created: NotRequired[Optional[str]] + created_by_user_name: NotRequired[Optional[str]] + products: NotRequired[Optional[List[str]]] + tags: NotRequired[Optional[Dict[str, str]]] + reference_parent_company: NotRequired[Optional[CompanyReferenceTypedDict]] + reference_subsidiary_companies: NotRequired[Optional[List[CompanyReferenceTypedDict]]] + data_connections: NotRequired[Optional[List[ConnectionTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/companyaccesstoken.py b/platform/src/codat_platform/models/shared/companyaccesstoken.py index 6d97a46d2..9cfd8d264 100644 --- a/platform/src/codat_platform/models/shared/companyaccesstoken.py +++ b/platform/src/codat_platform/models/shared/companyaccesstoken.py @@ -1,36 +1,105 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import BaseModel -import pydantic -from typing_extensions import Annotated, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class CompanyAccessTokenTypedDict(TypedDict): - r"""Details of the access token provisioned for a company.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 - access_token: str - r"""The access token for the company.""" - expires_in: int - r"""The number of seconds until the access token expires.""" - token_type: str - r"""The type of token.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class CompanyAccessToken(BaseModel): - r"""Details of the access token provisioned for a company.""" - access_token: Annotated[str, pydantic.Field(alias="accessToken")] - r"""The access token for the company.""" + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + Details of the access token provisioned for a company. + """ # noqa: E501 + expires_in: int = Field(description="The number of seconds until the access token expires.", alias="expiresIn") + access_token: str = Field(description="The access token for the company.", alias="accessToken") + token_type: str = Field(description="The type of token.", alias="tokenType") + __properties: ClassVar[List[str]] = ["expiresIn", "accessToken", "tokenType"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyAccessToken from a JSON string""" + return cls.from_dict(json.loads(json_str)) - expires_in: Annotated[int, pydantic.Field(alias="expiresIn")] - r"""The number of seconds until the access token expires.""" + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - token_type: Annotated[str, pydantic.Field(alias="tokenType")] - r"""The type of token.""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) -try: - CompanyAccessToken.model_rebuild() -except NameError: - pass + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyAccessToken from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "expiresIn": obj.get("expiresIn"), + "accessToken": obj.get("accessToken"), + "tokenType": obj.get("tokenType") + }) + return _obj + + + + + +class CompanyAccessTokenTypedDict(TypedDict): + """TypedDict variant of CompanyAccessToken, for dict-literal request/response inputs.""" + expires_in: NotRequired[int] + access_token: NotRequired[str] + token_type: NotRequired[str] diff --git a/platform/src/codat_platform/models/shared/companydetails.py b/platform/src/codat_platform/models/shared/companydetails.py index 4057d5798..d0d599bc2 100644 --- a/platform/src/codat_platform/models/shared/companydetails.py +++ b/platform/src/codat_platform/models/shared/companydetails.py @@ -1,198 +1,146 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .companyreference import CompanyReference, CompanyReferenceTypedDict -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Dict, List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class CompanyDetailsTypedDict(TypedDict): - id: str - r"""Unique identifier for your SMB in Codat.""" - name: str - r"""The name of the company""" - redirect: str - r"""The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company.""" - created: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - created_by_user_name: NotRequired[Nullable[str]] - r"""Name of user that created the company in Codat.""" - description: NotRequired[str] - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - last_sync: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - + Do not edit the class manually. +""" # noqa: E501 - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - products: NotRequired[List[str]] - r"""An array of products that are currently enabled for the company.""" - reference_parent_company: NotRequired[CompanyReferenceTypedDict] - reference_subsidiary_companies: NotRequired[List[CompanyReferenceTypedDict]] - r"""A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children.""" - tags: NotRequired[Dict[str, str]] - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.companyreference import CompanyReference, CompanyReferenceTypedDict +from typing import Optional, Set +from typing_extensions import Self +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL class CompanyDetails(BaseModel): - id: str - r"""Unique identifier for your SMB in Codat.""" - - name: str - r"""The name of the company""" - - redirect: str - r"""The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company.""" - - created: Optional[str] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - - created_by_user_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="createdByUserName") - ] = UNSET - r"""Name of user that created the company in Codat.""" - - description: Optional[str] = None - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - - last_sync: Annotated[Optional[str], pydantic.Field(alias="lastSync")] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'createdByUserName', 'created_by_user_name'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ + CompanyDetails + """ # noqa: E501 + id: str = Field(description="Unique identifier for your SMB in Codat.") + name: str = Field(description="The name of the company") + description: Optional[str] = Field(default=None, description="A description of the property.") + redirect: str = Field(description="The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company.") + last_sync: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="lastSync") + created: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.") + created_by_user_name: OptionalNullable[str] = Field(default=UNSET, description="Name of user that created the company in Codat.", alias="createdByUserName") + products: Optional[List[str]] = Field(default=None, description="An array of products that are currently enabled for the company.") + tags: Optional[Dict[str, str]] = Field(default=None, description="A collection of user-defined key-value pairs that store custom metadata against the company.") + reference_parent_company: Optional[CompanyReference] = Field(default=None, description="The parent entity or controlling organization of this company. Null if the company has no parent.", alias="referenceParentCompany") + reference_subsidiary_companies: Optional[List[CompanyReference]] = Field(default=None, description="A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children.", alias="referenceSubsidiaryCompanies") + __properties: ClassVar[List[str]] = ["id", "name", "description", "redirect", "lastSync", "created", "createdByUserName", "products", "tags", "referenceParentCompany", "referenceSubsidiaryCompanies"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyDetails from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of reference_parent_company + if self.reference_parent_company: + _dict['referenceParentCompany'] = self.reference_parent_company.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in reference_subsidiary_companies (list) + _items = [] + if self.reference_subsidiary_companies: + for _item_reference_subsidiary_companies in self.reference_subsidiary_companies: + if _item_reference_subsidiary_companies: + _items.append(_item_reference_subsidiary_companies.to_dict()) + _dict['referenceSubsidiaryCompanies'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyDetails from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "description": obj.get("description"), + "redirect": obj.get("redirect"), + "lastSync": obj.get("lastSync"), + "created": obj.get("created"), + "createdByUserName": obj.get("createdByUserName"), + "products": obj.get("products"), + "tags": obj.get("tags"), + "referenceParentCompany": CompanyReference.from_dict(obj["referenceParentCompany"]) if obj.get("referenceParentCompany") is not None else None, + "referenceSubsidiaryCompanies": [CompanyReference.from_dict(_item) for _item in obj["referenceSubsidiaryCompanies"]] if obj.get("referenceSubsidiaryCompanies") is not None else None + }) + return _obj - products: Optional[List[str]] = None - r"""An array of products that are currently enabled for the company.""" - reference_parent_company: Annotated[ - Optional[CompanyReference], pydantic.Field(alias="referenceParentCompany") - ] = None - reference_subsidiary_companies: Annotated[ - Optional[List[CompanyReference]], - pydantic.Field(alias="referenceSubsidiaryCompanies"), - ] = None - r"""A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children.""" - tags: Optional[Dict[str, str]] = None - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "created", - "createdByUserName", - "description", - "lastSync", - "products", - "referenceParentCompany", - "referenceSubsidiaryCompanies", - "tags", - ] - ) - nullable_fields = set(["createdByUserName"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - CompanyDetails.model_rebuild() -except NameError: - pass +class CompanyDetailsTypedDict(TypedDict): + """TypedDict variant of CompanyDetails, for dict-literal request/response inputs.""" + id: NotRequired[str] + name: NotRequired[str] + description: NotRequired[Optional[str]] + redirect: NotRequired[str] + last_sync: NotRequired[Optional[str]] + created: NotRequired[Optional[str]] + created_by_user_name: NotRequired[Optional[str]] + products: NotRequired[Optional[List[str]]] + tags: NotRequired[Optional[Dict[str, str]]] + reference_parent_company: NotRequired[Optional[CompanyReferenceTypedDict]] + reference_subsidiary_companies: NotRequired[Optional[List[CompanyReferenceTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/companyreference.py b/platform/src/codat_platform/models/shared/companyreference.py index 1396b267f..a072f64d4 100644 --- a/platform/src/codat_platform/models/shared/companyreference.py +++ b/platform/src/codat_platform/models/shared/companyreference.py @@ -1,83 +1,116 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Dict, Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) -class CompanyReferenceLinksTypedDict(TypedDict): - r"""A collection of links for the company.""" + Do not edit the class manually. +""" # noqa: E501 - portal: NotRequired[str] - r"""Link to the company page in the portal.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json -class CompanyReferenceLinks(BaseModel): - r"""A collection of links for the company.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.company_reference_links import CompanyReferenceLinks, CompanyReferenceLinksTypedDict +from typing import Optional, Set +from typing_extensions import Self - portal: Optional[str] = None - r"""Link to the company page in the portal.""" +class CompanyReference(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["portal"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + CompanyReference + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier for your SMB in Codat.") + name: Optional[str] = Field(default=None, description="A meaningful name assigned to the API key.") + description: Optional[str] = Field(default=None, description="A description of the property.") + links: Optional[CompanyReferenceLinks] = None + tags: Optional[Dict[str, str]] = Field(default=None, description="A collection of user-defined key-value pairs that store custom metadata against the company.") + __properties: ClassVar[List[str]] = ["id", "name", "description", "links", "tags"] - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) -class CompanyReferenceTypedDict(TypedDict): - description: NotRequired[str] - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - id: NotRequired[str] - r"""Unique identifier for your SMB in Codat.""" - links: NotRequired[CompanyReferenceLinksTypedDict] - r"""A collection of links for the company.""" - name: NotRequired[str] - r"""The name of the company""" - tags: NotRequired[Dict[str, str]] - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyReference from a JSON string""" + return cls.from_dict(json.loads(json_str)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. -class CompanyReference(BaseModel): - description: Optional[str] = None - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - id: Optional[str] = None - r"""Unique identifier for your SMB in Codat.""" + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - links: Optional[CompanyReferenceLinks] = None - r"""A collection of links for the company.""" + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['links'] = self.links.to_dict() + return _dict - name: Optional[str] = None - r"""The name of the company""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyReference from a dict""" + if obj is None: + return None - tags: Optional[Dict[str, str]] = None - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" + if not isinstance(obj, dict): + return cls.model_validate(obj) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["description", "id", "links", "name", "tags"]) - serialized = handler(self) - m = {} + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "description": obj.get("description"), + "links": CompanyReferenceLinks.from_dict(obj["links"]) if obj.get("links") is not None else None, + "tags": obj.get("tags") + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m + + +class CompanyReferenceTypedDict(TypedDict): + """TypedDict variant of CompanyReference, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + description: NotRequired[Optional[str]] + links: NotRequired[Optional[CompanyReferenceLinksTypedDict]] + tags: NotRequired[Optional[Dict[str, str]]] diff --git a/platform/src/codat_platform/models/shared/companyrequestbody.py b/platform/src/codat_platform/models/shared/companyrequestbody.py index 8c822ec12..03e001e2a 100644 --- a/platform/src/codat_platform/models/shared/companyrequestbody.py +++ b/platform/src/codat_platform/models/shared/companyrequestbody.py @@ -1,43 +1,113 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Dict, Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class CompanyRequestBodyTypedDict(TypedDict): - name: str - r"""Name of company being connected.""" - description: NotRequired[str] - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - tags: NotRequired[Dict[str, str]] - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class CompanyRequestBody(BaseModel): - name: str - r"""Name of company being connected.""" - description: Optional[str] = None - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from typing import Optional, Set +from typing_extensions import Self - tags: Optional[Dict[str, str]] = None - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" +class CompanyRequestBody(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["description", "tags"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + CompanyRequestBody + """ # noqa: E501 + name: str = Field(description="Name of company being connected.") + description: Optional[str] = Field(default=None, description="Additional information about the company. This can be used to store foreign IDs, references, etc.") + tags: Optional[Dict[str, str]] = Field(default=None, description="A collection of user-defined key-value pairs that store custom metadata against the company.") + __properties: ClassVar[List[str]] = ["name", "description", "tags"] + + @field_validator('name') + def name_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^[A-Za-z0-9\s\-\',&@.,?!\s]+$", value): + raise ValueError(r"must validate the regular expression /^[A-Za-z0-9\s\-',&@.,?!\s]+$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyRequestBody from a JSON string""" + return cls.from_dict(json.loads(json_str)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - return m + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyRequestBody from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "description": obj.get("description"), + "tags": obj.get("tags") + }) + return _obj + + + + + +class CompanyRequestBodyTypedDict(TypedDict): + """TypedDict variant of CompanyRequestBody, for dict-literal request/response inputs.""" + name: NotRequired[str] + description: NotRequired[Optional[str]] + tags: NotRequired[Optional[Dict[str, str]]] diff --git a/platform/src/codat_platform/models/shared/companysyncsettings.py b/platform/src/codat_platform/models/shared/companysyncsettings.py index f66ac8057..7421b5a9f 100644 --- a/platform/src/codat_platform/models/shared/companysyncsettings.py +++ b/platform/src/codat_platform/models/shared/companysyncsettings.py @@ -1,51 +1,113 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .syncsetting import SyncSetting, SyncSettingTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class CompanySyncSettingsTypedDict(TypedDict): - company_id: NotRequired[str] - r"""Unique identifier for your SMB in Codat.""" - overrides_defaults: NotRequired[bool] - r"""Set to `True` if you want to override the default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings).""" - settings: NotRequired[List[SyncSettingTypedDict]] + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class CompanySyncSettings(BaseModel): - company_id: Annotated[Optional[str], pydantic.Field(alias="companyId")] = None - r"""Unique identifier for your SMB in Codat.""" - overrides_defaults: Annotated[ - Optional[bool], pydantic.Field(alias="overridesDefaults") - ] = None - r"""Set to `True` if you want to override the default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings).""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - settings: Optional[List[SyncSetting]] = None +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.syncsetting import SyncSetting, SyncSettingTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class CompanySyncSettings(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["companyId", "overridesDefaults", "settings"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + CompanySyncSettings + """ # noqa: E501 + company_id: Optional[str] = Field(default=None, description="Unique identifier for your SMB in Codat.", alias="companyId") + settings: Optional[List[SyncSetting]] = None + overrides_defaults: Optional[bool] = Field(default=None, description="Set to `True` if you want to override the default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings).", alias="overridesDefaults") + __properties: ClassVar[List[str]] = ["companyId", "settings", "overridesDefaults"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanySyncSettings from a JSON string""" + return cls.from_dict(json.loads(json_str)) - return m + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: -try: - CompanySyncSettings.model_rebuild() -except NameError: - pass + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in settings (list) + _items = [] + if self.settings: + for _item_settings in self.settings: + if _item_settings: + _items.append(_item_settings.to_dict()) + _dict['settings'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanySyncSettings from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "companyId": obj.get("companyId"), + "settings": [SyncSetting.from_dict(_item) for _item in obj["settings"]] if obj.get("settings") is not None else None, + "overridesDefaults": obj.get("overridesDefaults") + }) + return _obj + + + + + +class CompanySyncSettingsTypedDict(TypedDict): + """TypedDict variant of CompanySyncSettings, for dict-literal request/response inputs.""" + company_id: NotRequired[Optional[str]] + settings: NotRequired[Optional[List[SyncSettingTypedDict]]] + overrides_defaults: NotRequired[Optional[bool]] diff --git a/platform/src/codat_platform/models/shared/companyupdaterequest.py b/platform/src/codat_platform/models/shared/companyupdaterequest.py index 2c26aa7ed..b64b625ba 100644 --- a/platform/src/codat_platform/models/shared/companyupdaterequest.py +++ b/platform/src/codat_platform/models/shared/companyupdaterequest.py @@ -1,43 +1,116 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Dict, Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class CompanyUpdateRequestTypedDict(TypedDict): - description: NotRequired[str] - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - name: NotRequired[str] - r"""Name of company being connected.""" - tags: NotRequired[Dict[str, str]] - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class CompanyUpdateRequest(BaseModel): - description: Optional[str] = None - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - name: Optional[str] = None - r"""Name of company being connected.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from typing import Optional, Set +from typing_extensions import Self - tags: Optional[Dict[str, str]] = None - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" +class CompanyUpdateRequest(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["description", "name", "tags"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + CompanyUpdateRequest + """ # noqa: E501 + name: Optional[str] = Field(default=None, description="Name of company being connected.") + description: Optional[str] = Field(default=None, description="A description of the property.") + tags: Optional[Dict[str, str]] = Field(default=None, description="A collection of user-defined key-value pairs that store custom metadata against the company.") + __properties: ClassVar[List[str]] = ["name", "description", "tags"] + + @field_validator('name') + def name_validate_regular_expression(cls, value): + """Validates the regular expression""" + if value is None: + return value + + if not re.match(r"^[A-Za-z0-9\s\-\',&@.,?!\s]+$", value): + raise ValueError(r"must validate the regular expression /^[A-Za-z0-9\s\-',&@.,?!\s]+$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyUpdateRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - return m + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyUpdateRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "description": obj.get("description"), + "tags": obj.get("tags") + }) + return _obj + + + + + +class CompanyUpdateRequestTypedDict(TypedDict): + """TypedDict variant of CompanyUpdateRequest, for dict-literal request/response inputs.""" + name: NotRequired[Optional[str]] + description: NotRequired[Optional[str]] + tags: NotRequired[Optional[Dict[str, str]]] diff --git a/platform/src/codat_platform/models/shared/companywebhook.py b/platform/src/codat_platform/models/shared/companywebhook.py index 403d3325e..1254233f8 100644 --- a/platform/src/codat_platform/models/shared/companywebhook.py +++ b/platform/src/codat_platform/models/shared/companywebhook.py @@ -1,94 +1,112 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .companydetails import CompanyDetails, CompanyDetailsTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class CompanyWebhookTypedDict(TypedDict): - event_type: NotRequired[str] - r"""The type of event.""" - generated_date: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.companydetails import CompanyDetails, CompanyDetailsTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` +class CompanyWebhook(BaseModel): - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} """ - id: NotRequired[str] - r"""Unique identifier of the event""" - payload: NotRequired[CompanyDetailsTypedDict] + CompanyWebhook + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the event") + event_type: Optional[str] = Field(default=None, description="The type of event.", alias="eventType") + generated_date: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="generatedDate") + payload: Optional[CompanyDetails] = None + __properties: ClassVar[List[str]] = ["id", "eventType", "generatedDate", "payload"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class CompanyWebhook(BaseModel): - event_type: Annotated[Optional[str], pydantic.Field(alias="eventType")] = None - r"""The type of event.""" - generated_date: Annotated[Optional[str], pydantic.Field(alias="generatedDate")] = ( - None - ) - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyWebhook from a JSON string""" + return cls.from_dict(json.loads(json_str)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of payload + if self.payload: + _dict['payload'] = self.payload.to_dict() + return _dict - id: Optional[str] = None - r"""Unique identifier of the event""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyWebhook from a dict""" + if obj is None: + return None - payload: Optional[CompanyDetails] = None + if not isinstance(obj, dict): + return cls.model_validate(obj) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["eventType", "generatedDate", "id", "payload"]) - serialized = handler(self) - m = {} + _obj = cls.model_validate({ + "id": obj.get("id"), + "eventType": obj.get("eventType"), + "generatedDate": obj.get("generatedDate"), + "payload": CompanyDetails.from_dict(obj["payload"]) if obj.get("payload") is not None else None + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - CompanyWebhook.model_rebuild() -except NameError: - pass +class CompanyWebhookTypedDict(TypedDict): + """TypedDict variant of CompanyWebhook, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + event_type: NotRequired[Optional[str]] + generated_date: NotRequired[Optional[str]] + payload: NotRequired[Optional[CompanyDetailsTypedDict]] diff --git a/platform/src/codat_platform/models/shared/connection.py b/platform/src/codat_platform/models/shared/connection.py index 9594c099c..69df2a1e4 100644 --- a/platform/src/codat_platform/models/shared/connection.py +++ b/platform/src/codat_platform/models/shared/connection.py @@ -1,218 +1,161 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from __future__ import annotations -from .dataconnectionerror import DataConnectionError, DataConnectionErrorTypedDict -from .dataconnectionstatus import DataConnectionStatus -from .sourcetype import SourceType -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Any, Dict, List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ConnectionTypedDict(TypedDict): - r"""A connection represents a [company's](https://docs.codat.io/platform-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source. - - A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to: - - - [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection. - - [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections. - - [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections. - Any combination of accounting, banking, and commerce data connections is allowed. - - Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). - """ - - created: str - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` +# coding: utf-8 +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - id: str - r"""Unique identifier for a company's data connection.""" - integration_id: str - r"""A Codat ID representing the integration.""" - link_url: str - r"""The link URL your customers can use to authorize access to their business application.""" - platform_name: str - r"""Name of integration connected to company.""" - source_id: str - r"""A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`.""" - source_type: SourceType - r"""The type of platform of the connection.""" - status: DataConnectionStatus - r"""The current authorization status of the data connection.""" - connection_info: NotRequired[Nullable[Dict[str, Any]]] - data_connection_errors: NotRequired[Nullable[List[DataConnectionErrorTypedDict]]] - integration_key: NotRequired[str] - r"""A unique four-character ID that identifies the platform of the company's data connection. This ensures continuity if the platform changes its name in the future.""" - last_sync: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.dataconnectionerror import DataConnectionError, DataConnectionErrorTypedDict +from codat_platform.models.shared.dataconnectionstatus import DataConnectionStatus +from codat_platform.models.shared.sourcetype import SourceType +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL class Connection(BaseModel): - r"""A connection represents a [company's](https://docs.codat.io/platform-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source. - - A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to: - - - [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection. - - [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections. - - [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections. - Any combination of accounting, banking, and commerce data connections is allowed. - - Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). - """ - - created: str - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'connectionInfo', 'connection_info', 'dataConnectionErrors', 'data_connection_errors'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - - id: str - r"""Unique identifier for a company's data connection.""" - - integration_id: Annotated[str, pydantic.Field(alias="integrationId")] - r"""A Codat ID representing the integration.""" - - link_url: Annotated[str, pydantic.Field(alias="linkUrl")] - r"""The link URL your customers can use to authorize access to their business application.""" - - platform_name: Annotated[str, pydantic.Field(alias="platformName")] - r"""Name of integration connected to company.""" - - source_id: Annotated[str, pydantic.Field(alias="sourceId")] - r"""A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`.""" - - source_type: Annotated[SourceType, pydantic.Field(alias="sourceType")] - r"""The type of platform of the connection.""" - + A connection represents a [company's](https://docs.codat.io/platform-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source. A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to: - [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection. - [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections. - [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections. Any combination of accounting, banking, and commerce data connections is allowed. Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). + """ # noqa: E501 + id: str = Field(description="Unique identifier for a company's data connection.") + integration_id: str = Field(description="A Codat ID representing the integration.", alias="integrationId") + integration_key: Optional[str] = Field(default=None, description="A unique four-character ID that identifies the platform of the company's data connection. This ensures continuity if the platform changes its name in the future.", alias="integrationKey") + source_id: str = Field(description="A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`.", alias="sourceId") + source_type: SourceType = Field(alias="sourceType") + platform_name: str = Field(description="Name of integration connected to company.", alias="platformName") + link_url: str = Field(description="The link URL your customers can use to authorize access to their business application.", alias="linkUrl") status: DataConnectionStatus - r"""The current authorization status of the data connection.""" - - connection_info: Annotated[ - OptionalNullable[Dict[str, Any]], pydantic.Field(alias="connectionInfo") - ] = UNSET - - data_connection_errors: Annotated[ - OptionalNullable[List[DataConnectionError]], - pydantic.Field(alias="dataConnectionErrors"), - ] = UNSET - - integration_key: Annotated[ - Optional[str], pydantic.Field(alias="integrationKey") - ] = None - r"""A unique four-character ID that identifies the platform of the company's data connection. This ensures continuity if the platform changes its name in the future.""" - - last_sync: Annotated[Optional[str], pydantic.Field(alias="lastSync")] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + last_sync: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="lastSync") + created: str = Field(description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.") + data_connection_errors: OptionalNullable[List[DataConnectionError]] = Field(default=UNSET, alias="dataConnectionErrors") + connection_info: OptionalNullable[Dict[str, Any]] = Field(default=UNSET, alias="connectionInfo") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["id", "integrationId", "integrationKey", "sourceId", "sourceType", "platformName", "linkUrl", "status", "lastSync", "created", "dataConnectionErrors", "connectionInfo"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Connection from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data_connection_errors (list) + _items = [] + if self.data_connection_errors: + for _item_data_connection_errors in self.data_connection_errors: + if _item_data_connection_errors: + _items.append(_item_data_connection_errors.to_dict()) + _dict['dataConnectionErrors'] = _items + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Connection from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "integrationId": obj.get("integrationId"), + "integrationKey": obj.get("integrationKey"), + "sourceId": obj.get("sourceId"), + "sourceType": obj.get("sourceType"), + "platformName": obj.get("platformName"), + "linkUrl": obj.get("linkUrl"), + "status": obj.get("status"), + "lastSync": obj.get("lastSync"), + "created": obj.get("created"), + "dataConnectionErrors": [DataConnectionError.from_dict(_item) for _item in obj["dataConnectionErrors"]] if obj.get("dataConnectionErrors") is not None else None, + "connectionInfo": obj.get("connectionInfo") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["connectionInfo", "dataConnectionErrors", "integrationKey", "lastSync"] - ) - nullable_fields = set(["connectionInfo", "dataConnectionErrors"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - Connection.model_rebuild() -except NameError: - pass +class ConnectionTypedDict(TypedDict): + """TypedDict variant of Connection, for dict-literal request/response inputs.""" + id: NotRequired[str] + integration_id: NotRequired[str] + integration_key: NotRequired[Optional[str]] + source_id: NotRequired[str] + source_type: NotRequired[SourceType] + platform_name: NotRequired[str] + link_url: NotRequired[str] + status: DataConnectionStatus + last_sync: NotRequired[Optional[str]] + created: NotRequired[str] + data_connection_errors: NotRequired[Optional[List[DataConnectionErrorTypedDict]]] + connection_info: NotRequired[Optional[Dict[str, Any]]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/platform/src/codat_platform/models/shared/connectionmanagementaccesstoken.py b/platform/src/codat_platform/models/shared/connectionmanagementaccesstoken.py index 39f35980d..c6c5c7257 100644 --- a/platform/src/codat_platform/models/shared/connectionmanagementaccesstoken.py +++ b/platform/src/codat_platform/models/shared/connectionmanagementaccesstoken.py @@ -1,40 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ConnectionManagementAccessTokenTypedDict(TypedDict): - access_token: NotRequired[str] - r"""Access token that allows SMBs to manage connections that have access to their data.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class ConnectionManagementAccessToken(BaseModel): - access_token: Annotated[Optional[str], pydantic.Field(alias="accessToken")] = None - r"""Access token that allows SMBs to manage connections that have access to their data.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["accessToken"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + ConnectionManagementAccessToken + """ # noqa: E501 + access_token: Optional[str] = Field(default=None, description="Access token that allows SMBs to manage connections that have access to their data.", alias="accessToken") + __properties: ClassVar[List[str]] = ["accessToken"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ConnectionManagementAccessToken from a JSON string""" + return cls.from_dict(json.loads(json_str)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - return m + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) -try: - ConnectionManagementAccessToken.model_rebuild() -except NameError: - pass + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ConnectionManagementAccessToken from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accessToken": obj.get("accessToken") + }) + return _obj + + + + + +class ConnectionManagementAccessTokenTypedDict(TypedDict): + """TypedDict variant of ConnectionManagementAccessToken, for dict-literal request/response inputs.""" + access_token: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/shared/connectionmanagementallowedorigins.py b/platform/src/codat_platform/models/shared/connectionmanagementallowedorigins.py index 4d6785fc5..271bf7b72 100644 --- a/platform/src/codat_platform/models/shared/connectionmanagementallowedorigins.py +++ b/platform/src/codat_platform/models/shared/connectionmanagementallowedorigins.py @@ -1,46 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ConnectionManagementAllowedOriginsTypedDict(TypedDict): - r"""Success""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - allowed_origins: NotRequired[List[str]] - r"""An array of allowed origins (i.e. your domains) to permit cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)).n resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)).""" + Do not edit the class manually. +""" # noqa: E501 -class ConnectionManagementAllowedOrigins(BaseModel): - r"""Success""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - allowed_origins: Annotated[ - Optional[List[str]], pydantic.Field(alias="allowedOrigins") - ] = None - r"""An array of allowed origins (i.e. your domains) to permit cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)).n resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)).""" +class ConnectionManagementAllowedOrigins(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["allowedOrigins"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + ConnectionManagementAllowedOrigins + """ # noqa: E501 + allowed_origins: Optional[List[str]] = Field(default=None, description="An array of allowed origins (i.e. your domains) to permit cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)).n resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)).", alias="allowedOrigins") + __properties: ClassVar[List[str]] = ["allowedOrigins"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ConnectionManagementAllowedOrigins from a JSON string""" + return cls.from_dict(json.loads(json_str)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - return m + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) -try: - ConnectionManagementAllowedOrigins.model_rebuild() -except NameError: - pass + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ConnectionManagementAllowedOrigins from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "allowedOrigins": obj.get("allowedOrigins") + }) + return _obj + + + + + +class ConnectionManagementAllowedOriginsTypedDict(TypedDict): + """TypedDict variant of ConnectionManagementAllowedOrigins, for dict-literal request/response inputs.""" + allowed_origins: NotRequired[Optional[List[str]]] diff --git a/platform/src/codat_platform/models/shared/connections.py b/platform/src/codat_platform/models/shared/connections.py index 83a7b5ff5..a7e6f3a6e 100644 --- a/platform/src/codat_platform/models/shared/connections.py +++ b/platform/src/codat_platform/models/shared/connections.py @@ -1,58 +1,124 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .connection import Connection, ConnectionTypedDict -from .links import Links, LinksTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.connection import Connection, ConnectionTypedDict +from codat_platform.models.shared.links import Links, LinksTypedDict +from typing import Optional, Set +from typing_extensions import Self +class Connections(BaseModel): -class ConnectionsTypedDict(TypedDict): - links: LinksTypedDict - page_number: int - r"""Current page number.""" - page_size: int - r"""Number of items to return in results array.""" - total_results: int - r"""Total number of items.""" - results: NotRequired[List[ConnectionTypedDict]] + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + Connections + """ # noqa: E501 + page_number: int = Field(description="Current page number.", alias="pageNumber") + page_size: int = Field(description="Number of items to return in results array.", alias="pageSize") + total_results: int = Field(description="Total number of items.", alias="totalResults") + links: Links = Field(alias="_links") + results: Optional[List[Connection]] = None + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links", "results"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class Connections(BaseModel): - links: Annotated[Links, pydantic.Field(alias="_links")] - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Connections from a JSON string""" + return cls.from_dict(json.loads(json_str)) - results: Optional[List[Connection]] = None + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["results"]) - serialized = handler(self) - m = {} + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['_links'] = self.links.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + return _dict - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Connections from a dict""" + if obj is None: + return None - return m + if not isinstance(obj, dict): + return cls.model_validate(obj) + _obj = cls.model_validate({ + "pageNumber": obj.get("pageNumber"), + "pageSize": obj.get("pageSize"), + "totalResults": obj.get("totalResults"), + "_links": Links.from_dict(obj["_links"]) if obj.get("_links") is not None else None, + "results": [Connection.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj -try: - Connections.model_rebuild() -except NameError: - pass + + + + +class ConnectionsTypedDict(TypedDict): + """TypedDict variant of Connections, for dict-literal request/response inputs.""" + page_number: NotRequired[int] + page_size: NotRequired[int] + total_results: NotRequired[int] + links: NotRequired[LinksTypedDict] + results: NotRequired[Optional[List[ConnectionTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/connectionwebhook.py b/platform/src/codat_platform/models/shared/connectionwebhook.py index fd864f131..c4306a389 100644 --- a/platform/src/codat_platform/models/shared/connectionwebhook.py +++ b/platform/src/codat_platform/models/shared/connectionwebhook.py @@ -1,97 +1,112 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .connectionwebhookpayload import ( - ConnectionWebhookPayload, - ConnectionWebhookPayloadTypedDict, -) -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ConnectionWebhookTypedDict(TypedDict): - event_type: NotRequired[str] - r"""The type of event.""" - generated_date: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.connectionwebhookpayload import ConnectionWebhookPayload, ConnectionWebhookPayloadTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` +class ConnectionWebhook(BaseModel): - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} """ - id: NotRequired[str] - r"""Unique identifier of the event.""" - payload: NotRequired[ConnectionWebhookPayloadTypedDict] + ConnectionWebhook + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the event.") + event_type: Optional[str] = Field(default=None, description="The type of event.", alias="eventType") + generated_date: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="generatedDate") + payload: Optional[ConnectionWebhookPayload] = None + __properties: ClassVar[List[str]] = ["id", "eventType", "generatedDate", "payload"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class ConnectionWebhook(BaseModel): - event_type: Annotated[Optional[str], pydantic.Field(alias="eventType")] = None - r"""The type of event.""" - generated_date: Annotated[Optional[str], pydantic.Field(alias="generatedDate")] = ( - None - ) - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ConnectionWebhook from a JSON string""" + return cls.from_dict(json.loads(json_str)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of payload + if self.payload: + _dict['payload'] = self.payload.to_dict() + return _dict - id: Optional[str] = None - r"""Unique identifier of the event.""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ConnectionWebhook from a dict""" + if obj is None: + return None - payload: Optional[ConnectionWebhookPayload] = None + if not isinstance(obj, dict): + return cls.model_validate(obj) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["eventType", "generatedDate", "id", "payload"]) - serialized = handler(self) - m = {} + _obj = cls.model_validate({ + "id": obj.get("id"), + "eventType": obj.get("eventType"), + "generatedDate": obj.get("generatedDate"), + "payload": ConnectionWebhookPayload.from_dict(obj["payload"]) if obj.get("payload") is not None else None + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - ConnectionWebhook.model_rebuild() -except NameError: - pass +class ConnectionWebhookTypedDict(TypedDict): + """TypedDict variant of ConnectionWebhook, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + event_type: NotRequired[Optional[str]] + generated_date: NotRequired[Optional[str]] + payload: NotRequired[Optional[ConnectionWebhookPayloadTypedDict]] diff --git a/platform/src/codat_platform/models/shared/connectionwebhookpayload.py b/platform/src/codat_platform/models/shared/connectionwebhookpayload.py index f85c6879c..45d387c65 100644 --- a/platform/src/codat_platform/models/shared/connectionwebhookpayload.py +++ b/platform/src/codat_platform/models/shared/connectionwebhookpayload.py @@ -1,67 +1,110 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .companyreference import CompanyReference, CompanyReferenceTypedDict -from .connection import Connection, ConnectionTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ConnectionWebhookPayloadTypedDict(TypedDict): - connection: NotRequired[ConnectionTypedDict] - r"""A connection represents a [company's](https://docs.codat.io/platform-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source. + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to: + Do not edit the class manually. +""" # noqa: E501 - - [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection. - - [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections. - - [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections. - Any combination of accounting, banking, and commerce data connections is allowed. - Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). - """ - reference_company: NotRequired[CompanyReferenceTypedDict] +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.companyreference import CompanyReference, CompanyReferenceTypedDict +from codat_platform.models.shared.connection import Connection, ConnectionTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class ConnectionWebhookPayload(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + ConnectionWebhookPayload + """ # noqa: E501 + reference_company: Optional[CompanyReference] = Field(default=None, alias="referenceCompany") connection: Optional[Connection] = None - r"""A connection represents a [company's](https://docs.codat.io/platform-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source. + __properties: ClassVar[List[str]] = ["referenceCompany", "connection"] - A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to: + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - - [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection. - - [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections. - - [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections. - Any combination of accounting, banking, and commerce data connections is allowed. - Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). - """ + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - reference_company: Annotated[ - Optional[CompanyReference], pydantic.Field(alias="referenceCompany") - ] = None + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["connection", "referenceCompany"]) - serialized = handler(self) - m = {} + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ConnectionWebhookPayload from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of reference_company + if self.reference_company: + _dict['referenceCompany'] = self.reference_company.to_dict() + # override the default output from pydantic by calling `to_dict()` of connection + if self.connection: + _dict['connection'] = self.connection.to_dict() + return _dict - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ConnectionWebhookPayload from a dict""" + if obj is None: + return None - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + if not isinstance(obj, dict): + return cls.model_validate(obj) - return m + _obj = cls.model_validate({ + "referenceCompany": CompanyReference.from_dict(obj["referenceCompany"]) if obj.get("referenceCompany") is not None else None, + "connection": Connection.from_dict(obj["connection"]) if obj.get("connection") is not None else None + }) + return _obj -try: - ConnectionWebhookPayload.model_rebuild() -except NameError: - pass + + + +class ConnectionWebhookPayloadTypedDict(TypedDict): + """TypedDict variant of ConnectionWebhookPayload, for dict-literal request/response inputs.""" + reference_company: NotRequired[Optional[CompanyReferenceTypedDict]] + connection: NotRequired[Optional[ConnectionTypedDict]] diff --git a/platform/src/codat_platform/models/shared/createapikey.py b/platform/src/codat_platform/models/shared/createapikey.py index 871b23864..7fd9800e4 100644 --- a/platform/src/codat_platform/models/shared/createapikey.py +++ b/platform/src/codat_platform/models/shared/createapikey.py @@ -1,51 +1,110 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from pydantic import model_serializer -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class CreateAPIKeyTypedDict(TypedDict): - r"""Details about the newly created API key.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - name: NotRequired[Nullable[str]] - r"""A meaningful name assigned to the API key.""" + Do not edit the class manually. +""" # noqa: E501 -class CreateAPIKey(BaseModel): - r"""Details about the newly created API key.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - name: OptionalNullable[str] = UNSET - r"""A meaningful name assigned to the API key.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from typing import Optional, Set +from typing_extensions import Self + +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL +class CreateAPIKey(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["name"]) - nullable_fields = set(["name"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m + _nullable = {'name'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + Details about the newly created API key. + """ # noqa: E501 + name: OptionalNullable[str] = Field(default=UNSET, description="A meaningful name assigned to the API key.") + __properties: ClassVar[List[str]] = ["name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CreateAPIKey from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateAPIKey from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name") + }) + return _obj + + + + + +class CreateAPIKeyTypedDict(TypedDict): + """TypedDict variant of CreateAPIKey, for dict-literal request/response inputs.""" + name: NotRequired[Optional[str]] + + +# POC spelling of CreateAPIKey, kept as an alias so existing imports keep working. +CreateApiKey = CreateAPIKey +CreateApiKeyTypedDict = CreateAPIKeyTypedDict diff --git a/platform/src/codat_platform/models/shared/customdatatypeconfiguration.py b/platform/src/codat_platform/models/shared/customdatatypeconfiguration.py index f96eb0cf2..d3fe552e5 100644 --- a/platform/src/codat_platform/models/shared/customdatatypeconfiguration.py +++ b/platform/src/codat_platform/models/shared/customdatatypeconfiguration.py @@ -1,80 +1,113 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Dict, List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -class CustomDataTypeConfigurationTypedDict(TypedDict): - r"""Client's configuration details for a specific custom data type and platform pair.""" - data_source: NotRequired[str] - r"""Underlying endpoint of the source platform that will serve as a data source for the custom data type. This value is not validated by Codat.""" - key_by: NotRequired[List[str]] - r"""An array of properties from the source system that can be used to uniquely identify the records returned for the custom data type. This value is not validated by Codat.""" - required_data: NotRequired[Dict[str, str]] - r"""Properties required to be fetched from the underlying platform for the custom data type that is being configured. This value is not validated by Codat.""" - source_modified_date: NotRequired[Nullable[List[str]]] - r"""Property in the source platform nominated by the client that defines the date when a record was last modified there. This value is not validated by Codat.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL class CustomDataTypeConfiguration(BaseModel): - r"""Client's configuration details for a specific custom data type and platform pair.""" - data_source: Annotated[Optional[str], pydantic.Field(alias="dataSource")] = None - r"""Underlying endpoint of the source platform that will serve as a data source for the custom data type. This value is not validated by Codat.""" + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'sourceModifiedDate', 'source_modified_date'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + Client's configuration details for a specific custom data type and platform pair. + """ # noqa: E501 + data_source: Optional[str] = Field(default=None, description="Underlying endpoint of the source platform that will serve as a data source for the custom data type. This value is not validated by Codat.", alias="dataSource") + required_data: Optional[Dict[str, str]] = Field(default=None, description="Properties required to be fetched from the underlying platform for the custom data type that is being configured. This value is not validated by Codat.", alias="requiredData") + key_by: Optional[List[str]] = Field(default=None, description="An array of properties from the source system that can be used to uniquely identify the records returned for the custom data type. This value is not validated by Codat.", alias="keyBy") + source_modified_date: OptionalNullable[List[str]] = Field(default=UNSET, description="Property in the source platform nominated by the client that defines the date when a record was last modified there. This value is not validated by Codat.", alias="sourceModifiedDate") + __properties: ClassVar[List[str]] = ["dataSource", "requiredData", "keyBy", "sourceModifiedDate"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CustomDataTypeConfiguration from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CustomDataTypeConfiguration from a dict""" + if obj is None: + return None - key_by: Annotated[Optional[List[str]], pydantic.Field(alias="keyBy")] = None - r"""An array of properties from the source system that can be used to uniquely identify the records returned for the custom data type. This value is not validated by Codat.""" + if not isinstance(obj, dict): + return cls.model_validate(obj) - required_data: Annotated[ - Optional[Dict[str, str]], pydantic.Field(alias="requiredData") - ] = None - r"""Properties required to be fetched from the underlying platform for the custom data type that is being configured. This value is not validated by Codat.""" + _obj = cls.model_validate({ + "dataSource": obj.get("dataSource"), + "requiredData": obj.get("requiredData"), + "keyBy": obj.get("keyBy"), + "sourceModifiedDate": obj.get("sourceModifiedDate") + }) + return _obj - source_modified_date: Annotated[ - OptionalNullable[List[str]], pydantic.Field(alias="sourceModifiedDate") - ] = UNSET - r"""Property in the source platform nominated by the client that defines the date when a record was last modified there. This value is not validated by Codat.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["dataSource", "keyBy", "requiredData", "sourceModifiedDate"] - ) - nullable_fields = set(["sourceModifiedDate"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - CustomDataTypeConfiguration.model_rebuild() -except NameError: - pass + + + +class CustomDataTypeConfigurationTypedDict(TypedDict): + """TypedDict variant of CustomDataTypeConfiguration, for dict-literal request/response inputs.""" + data_source: NotRequired[Optional[str]] + required_data: NotRequired[Optional[Dict[str, str]]] + key_by: NotRequired[Optional[List[str]]] + source_modified_date: NotRequired[Optional[List[str]]] diff --git a/platform/src/codat_platform/models/shared/customdatatyperecord.py b/platform/src/codat_platform/models/shared/customdatatyperecord.py index 1553f9940..87cc33ff1 100644 --- a/platform/src/codat_platform/models/shared/customdatatyperecord.py +++ b/platform/src/codat_platform/models/shared/customdatatyperecord.py @@ -1,86 +1,110 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Dict, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ContentTypedDict(TypedDict): - pass - - -class Content(BaseModel): - pass +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ModifiedDateTypedDict(TypedDict): - modified_date: NotRequired[str] + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class ModifiedDate(BaseModel): - modified_date: Annotated[Optional[str], pydantic.Field(alias="modifiedDate")] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["modifiedDate"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m - - -class CustomDataTypeRecordTypedDict(TypedDict): - content: NotRequired[Dict[str, ContentTypedDict]] - r"""Values from the source system for the properties defined in the custom data type configuration.""" - id: NotRequired[str] - r"""Unique identifier of the record.""" - modified_date: NotRequired[ModifiedDateTypedDict] +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.modified_date import ModifiedDate, ModifiedDateTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict +from codat_platform.models.content import Content, ContentTypedDict class CustomDataTypeRecord(BaseModel): - content: Optional[Dict[str, Content]] = None - r"""Values from the source system for the properties defined in the custom data type configuration.""" - - id: Optional[str] = None - r"""Unique identifier of the record.""" - - modified_date: Annotated[ - Optional[ModifiedDate], pydantic.Field(alias="modifiedDate") - ] = None @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["content", "id", "modifiedDate"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + CustomDataTypeRecord + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the record.") + content: Optional[Dict[str, Content]] = Field(default=None, description="Values from the source system for the properties defined in the custom data type configuration.") + modified_date: Optional[ModifiedDate] = Field(default=None, alias="modifiedDate") + __properties: ClassVar[List[str]] = ["id", "content", "modifiedDate"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CustomDataTypeRecord from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of modified_date + if self.modified_date: + _dict['modifiedDate'] = self.modified_date.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CustomDataTypeRecord from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "content": obj.get("content"), + "modifiedDate": ModifiedDate.from_dict(obj["modifiedDate"]) if obj.get("modifiedDate") is not None else None + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - ModifiedDate.model_rebuild() -except NameError: - pass -try: - CustomDataTypeRecord.model_rebuild() -except NameError: - pass +class CustomDataTypeRecordTypedDict(TypedDict): + """TypedDict variant of CustomDataTypeRecord, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + content: NotRequired[Optional[Dict[str, ContentTypedDict]]] + modified_date: NotRequired[Optional[ModifiedDateTypedDict]] diff --git a/platform/src/codat_platform/models/shared/customdatatyperecords.py b/platform/src/codat_platform/models/shared/customdatatyperecords.py index 8831646ae..ad27fbbda 100644 --- a/platform/src/codat_platform/models/shared/customdatatyperecords.py +++ b/platform/src/codat_platform/models/shared/customdatatyperecords.py @@ -1,58 +1,117 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from __future__ import annotations -from .customdatatyperecord import CustomDataTypeRecord, CustomDataTypeRecordTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +# coding: utf-8 +""" + Platform API -class CustomDataTypeRecordsTypedDict(TypedDict): - r"""Resulting records pulled from the source platform for a specific custom data type.""" - - page_number: NotRequired[int] - r"""Current page number.""" - page_size: NotRequired[int] - r"""Number of items to return in results array.""" - results: NotRequired[List[CustomDataTypeRecordTypedDict]] - total_results: NotRequired[int] - r"""Total number of items.""" + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) -class CustomDataTypeRecords(BaseModel): - r"""Resulting records pulled from the source platform for a specific custom data type.""" + Do not edit the class manually. +""" # noqa: E501 - page_number: Annotated[Optional[int], pydantic.Field(alias="pageNumber")] = None - r"""Current page number.""" - page_size: Annotated[Optional[int], pydantic.Field(alias="pageSize")] = None - r"""Number of items to return in results array.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - results: Optional[List[CustomDataTypeRecord]] = None +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.customdatatyperecord import CustomDataTypeRecord, CustomDataTypeRecordTypedDict +from typing import Optional, Set +from typing_extensions import Self - total_results: Annotated[Optional[int], pydantic.Field(alias="totalResults")] = None - r"""Total number of items.""" +class CustomDataTypeRecords(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["pageNumber", "pageSize", "results", "totalResults"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Resulting records pulled from the source platform for a specific custom data type. + """ # noqa: E501 + results: Optional[List[CustomDataTypeRecord]] = None + page_number: Optional[int] = Field(default=None, description="Current page number.", alias="pageNumber") + page_size: Optional[int] = Field(default=None, description="Number of items to return in results array.", alias="pageSize") + total_results: Optional[int] = Field(default=None, description="Total number of items.", alias="totalResults") + __properties: ClassVar[List[str]] = ["results", "pageNumber", "pageSize", "totalResults"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CustomDataTypeRecords from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CustomDataTypeRecords from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "results": [CustomDataTypeRecord.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None, + "pageNumber": obj.get("pageNumber"), + "pageSize": obj.get("pageSize"), + "totalResults": obj.get("totalResults") + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - CustomDataTypeRecords.model_rebuild() -except NameError: - pass +class CustomDataTypeRecordsTypedDict(TypedDict): + """TypedDict variant of CustomDataTypeRecords, for dict-literal request/response inputs.""" + results: NotRequired[Optional[List[CustomDataTypeRecordTypedDict]]] + page_number: NotRequired[Optional[int]] + page_size: NotRequired[Optional[int]] + total_results: NotRequired[Optional[int]] diff --git a/platform/src/codat_platform/models/shared/dataconnectionerror.py b/platform/src/codat_platform/models/shared/dataconnectionerror.py index f6c0b2845..8ae46858f 100644 --- a/platform/src/codat_platform/models/shared/dataconnectionerror.py +++ b/platform/src/codat_platform/models/shared/dataconnectionerror.py @@ -1,177 +1,130 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from enum import Enum -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ErrorStatus(str, Enum): - r"""The current status of a transient error. Null statuses indicate that the error is not transient.""" - - ACTIVE = "Active" - RESOLVED = "Resolved" - - -class DataConnectionErrorTypedDict(TypedDict): - error_message: NotRequired[str] - r"""A message about a error returned by Codat.""" - errored_on_utc: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - resolved_on_utc: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + Do not edit the class manually. +""" # noqa: E501 - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - status: NotRequired[Nullable[ErrorStatus]] - r"""The current status of a transient error. Null statuses indicate that the error is not transient.""" - status_code: NotRequired[str] - r"""The HTTP status code returned by the source platform when the error occurred.""" - status_text: NotRequired[str] - r"""A non-numeric status code/text returned by the source platform when the error occurred.""" +from __future__ import annotations +from codat_platform.models.error_status import ErrorStatus +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL class DataConnectionError(BaseModel): - error_message: Annotated[Optional[str], pydantic.Field(alias="errorMessage")] = None - r"""A message about a error returned by Codat.""" - errored_on_utc: Annotated[Optional[str], pydantic.Field(alias="erroredOnUtc")] = ( - None + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'status'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + DataConnectionError + """ # noqa: E501 + status_code: Optional[str] = Field(default=None, description="The HTTP status code returned by the source platform when the error occurred.", alias="statusCode") + status_text: Optional[str] = Field(default=None, description="A non-numeric status code/text returned by the source platform when the error occurred.", alias="statusText") + error_message: Optional[str] = Field(default=None, description="A message about a error returned by Codat.", alias="errorMessage") + errored_on_utc: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="erroredOnUtc") + status: OptionalNullable[ErrorStatus] = Field(default=UNSET, description="The current status of a transient error. Null statuses indicate that the error is not transient.") + resolved_on_utc: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="resolvedOnUtc") + __properties: ClassVar[List[str]] = ["statusCode", "statusText", "errorMessage", "erroredOnUtc", "status", "resolvedOnUtc"] + + @field_validator('status') + def status_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['Active', 'Resolved']): + raise ValueError("must be one of enum values ('Active', 'Resolved')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), ) - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DataConnectionError from a JSON string""" + return cls.from_dict(json.loads(json_str)) - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - resolved_on_utc: Annotated[Optional[str], pydantic.Field(alias="resolvedOnUtc")] = ( - None - ) - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DataConnectionError from a dict""" + if obj is None: + return None - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + if not isinstance(obj, dict): + return cls.model_validate(obj) - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` + _obj = cls.model_validate({ + "statusCode": obj.get("statusCode"), + "statusText": obj.get("statusText"), + "errorMessage": obj.get("errorMessage"), + "erroredOnUtc": obj.get("erroredOnUtc"), + "status": obj.get("status"), + "resolvedOnUtc": obj.get("resolvedOnUtc") + }) + return _obj - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - status: OptionalNullable[ErrorStatus] = UNSET - r"""The current status of a transient error. Null statuses indicate that the error is not transient.""" - status_code: Annotated[Optional[str], pydantic.Field(alias="statusCode")] = None - r"""The HTTP status code returned by the source platform when the error occurred.""" - status_text: Annotated[Optional[str], pydantic.Field(alias="statusText")] = None - r"""A non-numeric status code/text returned by the source platform when the error occurred.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "errorMessage", - "erroredOnUtc", - "resolvedOnUtc", - "status", - "statusCode", - "statusText", - ] - ) - nullable_fields = set(["status"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - DataConnectionError.model_rebuild() -except NameError: - pass +class DataConnectionErrorTypedDict(TypedDict): + """TypedDict variant of DataConnectionError, for dict-literal request/response inputs.""" + status_code: NotRequired[Optional[str]] + status_text: NotRequired[Optional[str]] + error_message: NotRequired[Optional[str]] + errored_on_utc: NotRequired[Optional[str]] + status: NotRequired[Optional[ErrorStatus]] + resolved_on_utc: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/shared/dataconnectionstatus.py b/platform/src/codat_platform/models/shared/dataconnectionstatus.py index a97f7be30..116be6582 100644 --- a/platform/src/codat_platform/models/shared/dataconnectionstatus.py +++ b/platform/src/codat_platform/models/shared/dataconnectionstatus.py @@ -1,13 +1,40 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class DataConnectionStatus(str, Enum): - r"""The current authorization status of the data connection.""" + """ + The current authorization status of the data connection. + """ + + """ + allowed enum values + """ + PENDING_AUTH = 'PendingAuth' + LINKED = 'Linked' + UNLINKED = 'Unlinked' + DEAUTHORIZED = 'Deauthorized' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of DataConnectionStatus from a JSON string""" + return cls(json.loads(json_str)) + - PENDING_AUTH = "PendingAuth" - LINKED = "Linked" - UNLINKED = "Unlinked" - DEAUTHORIZED = "Deauthorized" diff --git a/platform/src/codat_platform/models/shared/datastatus.py b/platform/src/codat_platform/models/shared/datastatus.py index f3c1069cf..e693c2a84 100644 --- a/platform/src/codat_platform/models/shared/datastatus.py +++ b/platform/src/codat_platform/models/shared/datastatus.py @@ -1,160 +1,128 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .status import Status -from codat_platform.types import BaseModel, UNSET_SENTINEL -from enum import Enum -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class DataTypes(str, Enum): - r"""Available data types""" - - ACCOUNT_TRANSACTIONS = "accountTransactions" - BALANCE_SHEET = "balanceSheet" - BANK_ACCOUNTS = "bankAccounts" - BANK_TRANSACTIONS = "bankTransactions" - BILL_CREDIT_NOTES = "billCreditNotes" - BILL_PAYMENTS = "billPayments" - BILLS = "bills" - CASH_FLOW_STATEMENT = "cashFlowStatement" - CHART_OF_ACCOUNTS = "chartOfAccounts" - COMPANY = "company" - CREDIT_NOTES = "creditNotes" - CUSTOMERS = "customers" - DIRECT_COSTS = "directCosts" - DIRECT_INCOMES = "directIncomes" - INVOICES = "invoices" - ITEM_RECEIPTS = "itemReceipts" - ITEMS = "items" - JOURNAL_ENTRIES = "journalEntries" - JOURNALS = "journals" - PAYMENT_METHODS = "paymentMethods" - PAYMENTS = "payments" - PROFIT_AND_LOSS = "profitAndLoss" - PURCHASE_ORDERS = "purchaseOrders" - SALES_ORDERS = "salesOrders" - SUPPLIERS = "suppliers" - TAX_RATES = "taxRates" - TRACKING_CATEGORIES = "trackingCategories" - TRANSFERS = "transfers" - BANKING_ACCOUNT_BALANCES = "banking-accountBalances" - BANKING_ACCOUNTS = "banking-accounts" - BANKING_TRANSACTION_CATEGORIES = "banking-transactionCategories" - BANKING_TRANSACTIONS = "banking-transactions" - COMMERCE_COMPANY_INFO = "commerce-companyInfo" - COMMERCE_CUSTOMERS = "commerce-customers" - COMMERCE_DISPUTES = "commerce-disputes" - COMMERCE_LOCATIONS = "commerce-locations" - COMMERCE_ORDERS = "commerce-orders" - COMMERCE_PAYMENT_METHODS = "commerce-paymentMethods" - COMMERCE_PAYMENTS = "commerce-payments" - COMMERCE_PRODUCT_CATEGORIES = "commerce-productCategories" - COMMERCE_PRODUCTS = "commerce-products" - COMMERCE_TAX_COMPONENTS = "commerce-taxComponents" - COMMERCE_TRANSACTIONS = "commerce-transactions" - - -class DataStatusTypedDict(TypedDict): - r"""Describes the state of data in the Codat cache for a company and data type""" - - current_status: Status - r"""The current status of the dataset.""" - data_type: DataTypes - r"""Available data types""" - last_successful_sync: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - latest_successful_sync_id: NotRequired[str] - r"""Unique identifier for the most recent successful sync of data type.""" - latest_sync_id: NotRequired[str] - r"""Unique identifier for most recent sync of data type.""" + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from codat_platform.models.current_status import CurrentStatus +from codat_platform.models.data_types import DataTypes +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_platform.models.shared.status import Status class DataStatus(BaseModel): - r"""Describes the state of data in the Codat cache for a company and data type""" - current_status: Annotated[Status, pydantic.Field(alias="currentStatus")] - r"""The current status of the dataset.""" + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + Describes the state of data in the Codat cache for a company and data type + """ # noqa: E501 + data_type: DataTypes = Field(description="Available data types", alias="dataType") + last_successful_sync: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="lastSuccessfulSync") + current_status: Status = Field(description="The current status of the dataset.", alias="currentStatus") + latest_sync_id: Optional[str] = Field(default=None, description="Unique identifier for most recent sync of data type.", alias="latestSyncId") + latest_successful_sync_id: Optional[str] = Field(default=None, description="Unique identifier for the most recent successful sync of data type.", alias="latestSuccessfulSyncId") + __properties: ClassVar[List[str]] = ["dataType", "lastSuccessfulSync", "currentStatus", "latestSyncId", "latestSuccessfulSyncId"] + + @field_validator('data_type') + def data_type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions']): + raise ValueError("must be one of enum values ('accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions')") + return value + + @field_validator('current_status') + def current_status_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['Initial', 'Queued', 'Fetching', 'MapQueued', 'Mapping', 'Complete', 'FetchError', 'MapError', 'InternalError', 'ProcessingQueued', 'Processing', 'ProcessingError', 'ValidationQueued', 'Validating', 'ValidationError', 'AuthError', 'Cancelled', 'NotSupported', 'RateLimitError', 'PermissionsError', 'PrerequisiteNotMet']): + raise ValueError("must be one of enum values ('Initial', 'Queued', 'Fetching', 'MapQueued', 'Mapping', 'Complete', 'FetchError', 'MapError', 'InternalError', 'ProcessingQueued', 'Processing', 'ProcessingError', 'ValidationQueued', 'Validating', 'ValidationError', 'AuthError', 'Cancelled', 'NotSupported', 'RateLimitError', 'PermissionsError', 'PrerequisiteNotMet')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - data_type: Annotated[DataTypes, pydantic.Field(alias="dataType")] - r"""Available data types""" - last_successful_sync: Annotated[ - Optional[str], pydantic.Field(alias="lastSuccessfulSync") - ] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DataStatus from a JSON string""" + return cls.from_dict(json.loads(json_str)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - latest_successful_sync_id: Annotated[ - Optional[str], pydantic.Field(alias="latestSuccessfulSyncId") - ] = None - r"""Unique identifier for the most recent successful sync of data type.""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DataStatus from a dict""" + if obj is None: + return None - latest_sync_id: Annotated[Optional[str], pydantic.Field(alias="latestSyncId")] = ( - None - ) - r"""Unique identifier for most recent sync of data type.""" + if not isinstance(obj, dict): + return cls.model_validate(obj) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["lastSuccessfulSync", "latestSuccessfulSyncId", "latestSyncId"] - ) - serialized = handler(self) - m = {} + _obj = cls.model_validate({ + "dataType": obj.get("dataType"), + "lastSuccessfulSync": obj.get("lastSuccessfulSync"), + "currentStatus": obj.get("currentStatus"), + "latestSyncId": obj.get("latestSyncId"), + "latestSuccessfulSyncId": obj.get("latestSuccessfulSyncId") + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - DataStatus.model_rebuild() -except NameError: - pass +class DataStatusTypedDict(TypedDict): + """TypedDict variant of DataStatus, for dict-literal request/response inputs.""" + data_type: NotRequired[DataTypes] + last_successful_sync: NotRequired[Optional[str]] + current_status: NotRequired[Status] + latest_sync_id: NotRequired[Optional[str]] + latest_successful_sync_id: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/shared/datastatuses.py b/platform/src/codat_platform/models/shared/datastatuses.py index 8bb61fb5b..6c780250f 100644 --- a/platform/src/codat_platform/models/shared/datastatuses.py +++ b/platform/src/codat_platform/models/shared/datastatuses.py @@ -1,363 +1,355 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .datastatus import DataStatus, DataStatusTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class DataStatusesTypedDict(TypedDict): - account_transactions: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - balance_sheet: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - bank_accounts: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - bank_transactions: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - banking_account_balances: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - banking_accounts: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - banking_transaction_categories: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - banking_transactions: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - bill_credit_notes: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - bill_payments: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - bills: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - cash_flow_statement: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - chart_of_accounts: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_company_info: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_customers: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_disputes: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_locations: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_orders: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_payment_methods: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_payments: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_product_categories: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_products: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_tax_components: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_transactions: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - company: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - credit_notes: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - customers: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - direct_costs: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - direct_incomes: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - invoices: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - item_receipts: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - items: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - journal_entries: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - journals: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - payment_methods: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - payments: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - profit_and_loss: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - purchase_orders: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - sales_orders: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - suppliers: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - tax_rates: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - tracking_categories: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - transfers: NotRequired[DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - - -class DataStatuses(BaseModel): - account_transactions: Annotated[ - Optional[DataStatus], pydantic.Field(alias="accountTransactions") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" +""" + Platform API - balance_sheet: Annotated[ - Optional[DataStatus], pydantic.Field(alias="balanceSheet") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | - bank_accounts: Annotated[ - Optional[DataStatus], pydantic.Field(alias="bankAccounts") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - bank_transactions: Annotated[ - Optional[DataStatus], pydantic.Field(alias="bankTransactions") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" + Do not edit the class manually. +""" # noqa: E501 - banking_account_balances: Annotated[ - Optional[DataStatus], pydantic.Field(alias="banking-accountBalances") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - banking_accounts: Annotated[ - Optional[DataStatus], pydantic.Field(alias="banking-accounts") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - banking_transaction_categories: Annotated[ - Optional[DataStatus], pydantic.Field(alias="banking-transactionCategories") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - banking_transactions: Annotated[ - Optional[DataStatus], pydantic.Field(alias="banking-transactions") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - bill_credit_notes: Annotated[ - Optional[DataStatus], pydantic.Field(alias="billCreditNotes") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.datastatus import DataStatus, DataStatusTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - bill_payments: Annotated[ - Optional[DataStatus], pydantic.Field(alias="billPayments") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" +class DataStatuses(BaseModel): + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + DataStatuses + """ # noqa: E501 + account_transactions: Optional[DataStatus] = Field(default=None, alias="accountTransactions") + balance_sheet: Optional[DataStatus] = Field(default=None, alias="balanceSheet") + bank_accounts: Optional[DataStatus] = Field(default=None, alias="bankAccounts") + bank_transactions: Optional[DataStatus] = Field(default=None, alias="bankTransactions") + bill_credit_notes: Optional[DataStatus] = Field(default=None, alias="billCreditNotes") + bill_payments: Optional[DataStatus] = Field(default=None, alias="billPayments") bills: Optional[DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - cash_flow_statement: Annotated[ - Optional[DataStatus], pydantic.Field(alias="cashFlowStatement") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - chart_of_accounts: Annotated[ - Optional[DataStatus], pydantic.Field(alias="chartOfAccounts") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_company_info: Annotated[ - Optional[DataStatus], pydantic.Field(alias="commerce-companyInfo") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_customers: Annotated[ - Optional[DataStatus], pydantic.Field(alias="commerce-customers") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_disputes: Annotated[ - Optional[DataStatus], pydantic.Field(alias="commerce-disputes") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_locations: Annotated[ - Optional[DataStatus], pydantic.Field(alias="commerce-locations") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_orders: Annotated[ - Optional[DataStatus], pydantic.Field(alias="commerce-orders") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_payment_methods: Annotated[ - Optional[DataStatus], pydantic.Field(alias="commerce-paymentMethods") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_payments: Annotated[ - Optional[DataStatus], pydantic.Field(alias="commerce-payments") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_product_categories: Annotated[ - Optional[DataStatus], pydantic.Field(alias="commerce-productCategories") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_products: Annotated[ - Optional[DataStatus], pydantic.Field(alias="commerce-products") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_tax_components: Annotated[ - Optional[DataStatus], pydantic.Field(alias="commerce-taxComponents") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_transactions: Annotated[ - Optional[DataStatus], pydantic.Field(alias="commerce-transactions") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - + cash_flow_statement: Optional[DataStatus] = Field(default=None, alias="cashFlowStatement") + chart_of_accounts: Optional[DataStatus] = Field(default=None, alias="chartOfAccounts") company: Optional[DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - credit_notes: Annotated[ - Optional[DataStatus], pydantic.Field(alias="creditNotes") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - + credit_notes: Optional[DataStatus] = Field(default=None, alias="creditNotes") customers: Optional[DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - direct_costs: Annotated[ - Optional[DataStatus], pydantic.Field(alias="directCosts") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - direct_incomes: Annotated[ - Optional[DataStatus], pydantic.Field(alias="directIncomes") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - + direct_costs: Optional[DataStatus] = Field(default=None, alias="directCosts") + direct_incomes: Optional[DataStatus] = Field(default=None, alias="directIncomes") invoices: Optional[DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - item_receipts: Annotated[ - Optional[DataStatus], pydantic.Field(alias="itemReceipts") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - + item_receipts: Optional[DataStatus] = Field(default=None, alias="itemReceipts") items: Optional[DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - journal_entries: Annotated[ - Optional[DataStatus], pydantic.Field(alias="journalEntries") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - + journal_entries: Optional[DataStatus] = Field(default=None, alias="journalEntries") journals: Optional[DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - payment_methods: Annotated[ - Optional[DataStatus], pydantic.Field(alias="paymentMethods") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - + payment_methods: Optional[DataStatus] = Field(default=None, alias="paymentMethods") payments: Optional[DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - profit_and_loss: Annotated[ - Optional[DataStatus], pydantic.Field(alias="profitAndLoss") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - purchase_orders: Annotated[ - Optional[DataStatus], pydantic.Field(alias="purchaseOrders") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - sales_orders: Annotated[ - Optional[DataStatus], pydantic.Field(alias="salesOrders") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - + profit_and_loss: Optional[DataStatus] = Field(default=None, alias="profitAndLoss") + purchase_orders: Optional[DataStatus] = Field(default=None, alias="purchaseOrders") + sales_orders: Optional[DataStatus] = Field(default=None, alias="salesOrders") suppliers: Optional[DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - tax_rates: Annotated[Optional[DataStatus], pydantic.Field(alias="taxRates")] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - tracking_categories: Annotated[ - Optional[DataStatus], pydantic.Field(alias="trackingCategories") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - + tax_rates: Optional[DataStatus] = Field(default=None, alias="taxRates") + tracking_categories: Optional[DataStatus] = Field(default=None, alias="trackingCategories") transfers: Optional[DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "accountTransactions", - "balanceSheet", - "bankAccounts", - "bankTransactions", - "banking-accountBalances", - "banking-accounts", - "banking-transactionCategories", - "banking-transactions", - "billCreditNotes", - "billPayments", - "bills", - "cashFlowStatement", - "chartOfAccounts", - "commerce-companyInfo", - "commerce-customers", - "commerce-disputes", - "commerce-locations", - "commerce-orders", - "commerce-paymentMethods", - "commerce-payments", - "commerce-productCategories", - "commerce-products", - "commerce-taxComponents", - "commerce-transactions", - "company", - "creditNotes", - "customers", - "directCosts", - "directIncomes", - "invoices", - "itemReceipts", - "items", - "journalEntries", - "journals", - "paymentMethods", - "payments", - "profitAndLoss", - "purchaseOrders", - "salesOrders", - "suppliers", - "taxRates", - "trackingCategories", - "transfers", - ] + banking_account_balances: Optional[DataStatus] = Field(default=None, alias="banking-accountBalances") + banking_accounts: Optional[DataStatus] = Field(default=None, alias="banking-accounts") + banking_transaction_categories: Optional[DataStatus] = Field(default=None, alias="banking-transactionCategories") + banking_transactions: Optional[DataStatus] = Field(default=None, alias="banking-transactions") + commerce_company_info: Optional[DataStatus] = Field(default=None, alias="commerce-companyInfo") + commerce_customers: Optional[DataStatus] = Field(default=None, alias="commerce-customers") + commerce_disputes: Optional[DataStatus] = Field(default=None, alias="commerce-disputes") + commerce_locations: Optional[DataStatus] = Field(default=None, alias="commerce-locations") + commerce_orders: Optional[DataStatus] = Field(default=None, alias="commerce-orders") + commerce_payment_methods: Optional[DataStatus] = Field(default=None, alias="commerce-paymentMethods") + commerce_payments: Optional[DataStatus] = Field(default=None, alias="commerce-payments") + commerce_product_categories: Optional[DataStatus] = Field(default=None, alias="commerce-productCategories") + commerce_products: Optional[DataStatus] = Field(default=None, alias="commerce-products") + commerce_tax_components: Optional[DataStatus] = Field(default=None, alias="commerce-taxComponents") + commerce_transactions: Optional[DataStatus] = Field(default=None, alias="commerce-transactions") + __properties: ClassVar[List[str]] = ["accountTransactions", "balanceSheet", "bankAccounts", "bankTransactions", "billCreditNotes", "billPayments", "bills", "cashFlowStatement", "chartOfAccounts", "company", "creditNotes", "customers", "directCosts", "directIncomes", "invoices", "itemReceipts", "items", "journalEntries", "journals", "paymentMethods", "payments", "profitAndLoss", "purchaseOrders", "salesOrders", "suppliers", "taxRates", "trackingCategories", "transfers", "banking-accountBalances", "banking-accounts", "banking-transactionCategories", "banking-transactions", "commerce-companyInfo", "commerce-customers", "commerce-disputes", "commerce-locations", "commerce-orders", "commerce-paymentMethods", "commerce-payments", "commerce-productCategories", "commerce-products", "commerce-taxComponents", "commerce-transactions"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DataStatuses from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - serialized = handler(self) - m = {} + # override the default output from pydantic by calling `to_dict()` of account_transactions + if self.account_transactions: + _dict['accountTransactions'] = self.account_transactions.to_dict() + # override the default output from pydantic by calling `to_dict()` of balance_sheet + if self.balance_sheet: + _dict['balanceSheet'] = self.balance_sheet.to_dict() + # override the default output from pydantic by calling `to_dict()` of bank_accounts + if self.bank_accounts: + _dict['bankAccounts'] = self.bank_accounts.to_dict() + # override the default output from pydantic by calling `to_dict()` of bank_transactions + if self.bank_transactions: + _dict['bankTransactions'] = self.bank_transactions.to_dict() + # override the default output from pydantic by calling `to_dict()` of bill_credit_notes + if self.bill_credit_notes: + _dict['billCreditNotes'] = self.bill_credit_notes.to_dict() + # override the default output from pydantic by calling `to_dict()` of bill_payments + if self.bill_payments: + _dict['billPayments'] = self.bill_payments.to_dict() + # override the default output from pydantic by calling `to_dict()` of bills + if self.bills: + _dict['bills'] = self.bills.to_dict() + # override the default output from pydantic by calling `to_dict()` of cash_flow_statement + if self.cash_flow_statement: + _dict['cashFlowStatement'] = self.cash_flow_statement.to_dict() + # override the default output from pydantic by calling `to_dict()` of chart_of_accounts + if self.chart_of_accounts: + _dict['chartOfAccounts'] = self.chart_of_accounts.to_dict() + # override the default output from pydantic by calling `to_dict()` of company + if self.company: + _dict['company'] = self.company.to_dict() + # override the default output from pydantic by calling `to_dict()` of credit_notes + if self.credit_notes: + _dict['creditNotes'] = self.credit_notes.to_dict() + # override the default output from pydantic by calling `to_dict()` of customers + if self.customers: + _dict['customers'] = self.customers.to_dict() + # override the default output from pydantic by calling `to_dict()` of direct_costs + if self.direct_costs: + _dict['directCosts'] = self.direct_costs.to_dict() + # override the default output from pydantic by calling `to_dict()` of direct_incomes + if self.direct_incomes: + _dict['directIncomes'] = self.direct_incomes.to_dict() + # override the default output from pydantic by calling `to_dict()` of invoices + if self.invoices: + _dict['invoices'] = self.invoices.to_dict() + # override the default output from pydantic by calling `to_dict()` of item_receipts + if self.item_receipts: + _dict['itemReceipts'] = self.item_receipts.to_dict() + # override the default output from pydantic by calling `to_dict()` of items + if self.items: + _dict['items'] = self.items.to_dict() + # override the default output from pydantic by calling `to_dict()` of journal_entries + if self.journal_entries: + _dict['journalEntries'] = self.journal_entries.to_dict() + # override the default output from pydantic by calling `to_dict()` of journals + if self.journals: + _dict['journals'] = self.journals.to_dict() + # override the default output from pydantic by calling `to_dict()` of payment_methods + if self.payment_methods: + _dict['paymentMethods'] = self.payment_methods.to_dict() + # override the default output from pydantic by calling `to_dict()` of payments + if self.payments: + _dict['payments'] = self.payments.to_dict() + # override the default output from pydantic by calling `to_dict()` of profit_and_loss + if self.profit_and_loss: + _dict['profitAndLoss'] = self.profit_and_loss.to_dict() + # override the default output from pydantic by calling `to_dict()` of purchase_orders + if self.purchase_orders: + _dict['purchaseOrders'] = self.purchase_orders.to_dict() + # override the default output from pydantic by calling `to_dict()` of sales_orders + if self.sales_orders: + _dict['salesOrders'] = self.sales_orders.to_dict() + # override the default output from pydantic by calling `to_dict()` of suppliers + if self.suppliers: + _dict['suppliers'] = self.suppliers.to_dict() + # override the default output from pydantic by calling `to_dict()` of tax_rates + if self.tax_rates: + _dict['taxRates'] = self.tax_rates.to_dict() + # override the default output from pydantic by calling `to_dict()` of tracking_categories + if self.tracking_categories: + _dict['trackingCategories'] = self.tracking_categories.to_dict() + # override the default output from pydantic by calling `to_dict()` of transfers + if self.transfers: + _dict['transfers'] = self.transfers.to_dict() + # override the default output from pydantic by calling `to_dict()` of banking_account_balances + if self.banking_account_balances: + _dict['banking-accountBalances'] = self.banking_account_balances.to_dict() + # override the default output from pydantic by calling `to_dict()` of banking_accounts + if self.banking_accounts: + _dict['banking-accounts'] = self.banking_accounts.to_dict() + # override the default output from pydantic by calling `to_dict()` of banking_transaction_categories + if self.banking_transaction_categories: + _dict['banking-transactionCategories'] = self.banking_transaction_categories.to_dict() + # override the default output from pydantic by calling `to_dict()` of banking_transactions + if self.banking_transactions: + _dict['banking-transactions'] = self.banking_transactions.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_company_info + if self.commerce_company_info: + _dict['commerce-companyInfo'] = self.commerce_company_info.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_customers + if self.commerce_customers: + _dict['commerce-customers'] = self.commerce_customers.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_disputes + if self.commerce_disputes: + _dict['commerce-disputes'] = self.commerce_disputes.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_locations + if self.commerce_locations: + _dict['commerce-locations'] = self.commerce_locations.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_orders + if self.commerce_orders: + _dict['commerce-orders'] = self.commerce_orders.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_payment_methods + if self.commerce_payment_methods: + _dict['commerce-paymentMethods'] = self.commerce_payment_methods.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_payments + if self.commerce_payments: + _dict['commerce-payments'] = self.commerce_payments.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_product_categories + if self.commerce_product_categories: + _dict['commerce-productCategories'] = self.commerce_product_categories.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_products + if self.commerce_products: + _dict['commerce-products'] = self.commerce_products.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_tax_components + if self.commerce_tax_components: + _dict['commerce-taxComponents'] = self.commerce_tax_components.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_transactions + if self.commerce_transactions: + _dict['commerce-transactions'] = self.commerce_transactions.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DataStatuses from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accountTransactions": DataStatus.from_dict(obj["accountTransactions"]) if obj.get("accountTransactions") is not None else None, + "balanceSheet": DataStatus.from_dict(obj["balanceSheet"]) if obj.get("balanceSheet") is not None else None, + "bankAccounts": DataStatus.from_dict(obj["bankAccounts"]) if obj.get("bankAccounts") is not None else None, + "bankTransactions": DataStatus.from_dict(obj["bankTransactions"]) if obj.get("bankTransactions") is not None else None, + "billCreditNotes": DataStatus.from_dict(obj["billCreditNotes"]) if obj.get("billCreditNotes") is not None else None, + "billPayments": DataStatus.from_dict(obj["billPayments"]) if obj.get("billPayments") is not None else None, + "bills": DataStatus.from_dict(obj["bills"]) if obj.get("bills") is not None else None, + "cashFlowStatement": DataStatus.from_dict(obj["cashFlowStatement"]) if obj.get("cashFlowStatement") is not None else None, + "chartOfAccounts": DataStatus.from_dict(obj["chartOfAccounts"]) if obj.get("chartOfAccounts") is not None else None, + "company": DataStatus.from_dict(obj["company"]) if obj.get("company") is not None else None, + "creditNotes": DataStatus.from_dict(obj["creditNotes"]) if obj.get("creditNotes") is not None else None, + "customers": DataStatus.from_dict(obj["customers"]) if obj.get("customers") is not None else None, + "directCosts": DataStatus.from_dict(obj["directCosts"]) if obj.get("directCosts") is not None else None, + "directIncomes": DataStatus.from_dict(obj["directIncomes"]) if obj.get("directIncomes") is not None else None, + "invoices": DataStatus.from_dict(obj["invoices"]) if obj.get("invoices") is not None else None, + "itemReceipts": DataStatus.from_dict(obj["itemReceipts"]) if obj.get("itemReceipts") is not None else None, + "items": DataStatus.from_dict(obj["items"]) if obj.get("items") is not None else None, + "journalEntries": DataStatus.from_dict(obj["journalEntries"]) if obj.get("journalEntries") is not None else None, + "journals": DataStatus.from_dict(obj["journals"]) if obj.get("journals") is not None else None, + "paymentMethods": DataStatus.from_dict(obj["paymentMethods"]) if obj.get("paymentMethods") is not None else None, + "payments": DataStatus.from_dict(obj["payments"]) if obj.get("payments") is not None else None, + "profitAndLoss": DataStatus.from_dict(obj["profitAndLoss"]) if obj.get("profitAndLoss") is not None else None, + "purchaseOrders": DataStatus.from_dict(obj["purchaseOrders"]) if obj.get("purchaseOrders") is not None else None, + "salesOrders": DataStatus.from_dict(obj["salesOrders"]) if obj.get("salesOrders") is not None else None, + "suppliers": DataStatus.from_dict(obj["suppliers"]) if obj.get("suppliers") is not None else None, + "taxRates": DataStatus.from_dict(obj["taxRates"]) if obj.get("taxRates") is not None else None, + "trackingCategories": DataStatus.from_dict(obj["trackingCategories"]) if obj.get("trackingCategories") is not None else None, + "transfers": DataStatus.from_dict(obj["transfers"]) if obj.get("transfers") is not None else None, + "banking-accountBalances": DataStatus.from_dict(obj["banking-accountBalances"]) if obj.get("banking-accountBalances") is not None else None, + "banking-accounts": DataStatus.from_dict(obj["banking-accounts"]) if obj.get("banking-accounts") is not None else None, + "banking-transactionCategories": DataStatus.from_dict(obj["banking-transactionCategories"]) if obj.get("banking-transactionCategories") is not None else None, + "banking-transactions": DataStatus.from_dict(obj["banking-transactions"]) if obj.get("banking-transactions") is not None else None, + "commerce-companyInfo": DataStatus.from_dict(obj["commerce-companyInfo"]) if obj.get("commerce-companyInfo") is not None else None, + "commerce-customers": DataStatus.from_dict(obj["commerce-customers"]) if obj.get("commerce-customers") is not None else None, + "commerce-disputes": DataStatus.from_dict(obj["commerce-disputes"]) if obj.get("commerce-disputes") is not None else None, + "commerce-locations": DataStatus.from_dict(obj["commerce-locations"]) if obj.get("commerce-locations") is not None else None, + "commerce-orders": DataStatus.from_dict(obj["commerce-orders"]) if obj.get("commerce-orders") is not None else None, + "commerce-paymentMethods": DataStatus.from_dict(obj["commerce-paymentMethods"]) if obj.get("commerce-paymentMethods") is not None else None, + "commerce-payments": DataStatus.from_dict(obj["commerce-payments"]) if obj.get("commerce-payments") is not None else None, + "commerce-productCategories": DataStatus.from_dict(obj["commerce-productCategories"]) if obj.get("commerce-productCategories") is not None else None, + "commerce-products": DataStatus.from_dict(obj["commerce-products"]) if obj.get("commerce-products") is not None else None, + "commerce-taxComponents": DataStatus.from_dict(obj["commerce-taxComponents"]) if obj.get("commerce-taxComponents") is not None else None, + "commerce-transactions": DataStatus.from_dict(obj["commerce-transactions"]) if obj.get("commerce-transactions") is not None else None + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - DataStatuses.model_rebuild() -except NameError: - pass +class DataStatusesTypedDict(TypedDict): + """TypedDict variant of DataStatuses, for dict-literal request/response inputs.""" + account_transactions: NotRequired[Optional[DataStatusTypedDict]] + balance_sheet: NotRequired[Optional[DataStatusTypedDict]] + bank_accounts: NotRequired[Optional[DataStatusTypedDict]] + bank_transactions: NotRequired[Optional[DataStatusTypedDict]] + bill_credit_notes: NotRequired[Optional[DataStatusTypedDict]] + bill_payments: NotRequired[Optional[DataStatusTypedDict]] + bills: NotRequired[Optional[DataStatusTypedDict]] + cash_flow_statement: NotRequired[Optional[DataStatusTypedDict]] + chart_of_accounts: NotRequired[Optional[DataStatusTypedDict]] + company: NotRequired[Optional[DataStatusTypedDict]] + credit_notes: NotRequired[Optional[DataStatusTypedDict]] + customers: NotRequired[Optional[DataStatusTypedDict]] + direct_costs: NotRequired[Optional[DataStatusTypedDict]] + direct_incomes: NotRequired[Optional[DataStatusTypedDict]] + invoices: NotRequired[Optional[DataStatusTypedDict]] + item_receipts: NotRequired[Optional[DataStatusTypedDict]] + items: NotRequired[Optional[DataStatusTypedDict]] + journal_entries: NotRequired[Optional[DataStatusTypedDict]] + journals: NotRequired[Optional[DataStatusTypedDict]] + payment_methods: NotRequired[Optional[DataStatusTypedDict]] + payments: NotRequired[Optional[DataStatusTypedDict]] + profit_and_loss: NotRequired[Optional[DataStatusTypedDict]] + purchase_orders: NotRequired[Optional[DataStatusTypedDict]] + sales_orders: NotRequired[Optional[DataStatusTypedDict]] + suppliers: NotRequired[Optional[DataStatusTypedDict]] + tax_rates: NotRequired[Optional[DataStatusTypedDict]] + tracking_categories: NotRequired[Optional[DataStatusTypedDict]] + transfers: NotRequired[Optional[DataStatusTypedDict]] + banking_account_balances: NotRequired[Optional[DataStatusTypedDict]] + banking_accounts: NotRequired[Optional[DataStatusTypedDict]] + banking_transaction_categories: NotRequired[Optional[DataStatusTypedDict]] + banking_transactions: NotRequired[Optional[DataStatusTypedDict]] + commerce_company_info: NotRequired[Optional[DataStatusTypedDict]] + commerce_customers: NotRequired[Optional[DataStatusTypedDict]] + commerce_disputes: NotRequired[Optional[DataStatusTypedDict]] + commerce_locations: NotRequired[Optional[DataStatusTypedDict]] + commerce_orders: NotRequired[Optional[DataStatusTypedDict]] + commerce_payment_methods: NotRequired[Optional[DataStatusTypedDict]] + commerce_payments: NotRequired[Optional[DataStatusTypedDict]] + commerce_product_categories: NotRequired[Optional[DataStatusTypedDict]] + commerce_products: NotRequired[Optional[DataStatusTypedDict]] + commerce_tax_components: NotRequired[Optional[DataStatusTypedDict]] + commerce_transactions: NotRequired[Optional[DataStatusTypedDict]] diff --git a/platform/src/codat_platform/models/shared/datatype.py b/platform/src/codat_platform/models/shared/datatype.py index e0aff6fb8..83cb38cee 100644 --- a/platform/src/codat_platform/models/shared/datatype.py +++ b/platform/src/codat_platform/models/shared/datatype.py @@ -1,52 +1,94 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class DataType(str, Enum): - r"""Available data types""" - - ACCOUNT_TRANSACTIONS = "accountTransactions" - BALANCE_SHEET = "balanceSheet" - BANK_ACCOUNTS = "bankAccounts" - BANK_TRANSACTIONS = "bankTransactions" - BILL_CREDIT_NOTES = "billCreditNotes" - BILL_PAYMENTS = "billPayments" - BILLS = "bills" - CASH_FLOW_STATEMENT = "cashFlowStatement" - CHART_OF_ACCOUNTS = "chartOfAccounts" - COMPANY = "company" - CREDIT_NOTES = "creditNotes" - CUSTOMERS = "customers" - DIRECT_COSTS = "directCosts" - DIRECT_INCOMES = "directIncomes" - INVOICES = "invoices" - ITEM_RECEIPTS = "itemReceipts" - ITEMS = "items" - JOURNAL_ENTRIES = "journalEntries" - JOURNALS = "journals" - PAYMENT_METHODS = "paymentMethods" - PAYMENTS = "payments" - PROFIT_AND_LOSS = "profitAndLoss" - PURCHASE_ORDERS = "purchaseOrders" - SALES_ORDERS = "salesOrders" - SUPPLIERS = "suppliers" - TAX_RATES = "taxRates" - TRACKING_CATEGORIES = "trackingCategories" - TRANSFERS = "transfers" - BANKING_ACCOUNT_BALANCES = "banking-accountBalances" - BANKING_ACCOUNTS = "banking-accounts" - BANKING_TRANSACTION_CATEGORIES = "banking-transactionCategories" - BANKING_TRANSACTIONS = "banking-transactions" - COMMERCE_COMPANY_INFO = "commerce-companyInfo" - COMMERCE_CUSTOMERS = "commerce-customers" - COMMERCE_DISPUTES = "commerce-disputes" - COMMERCE_LOCATIONS = "commerce-locations" - COMMERCE_ORDERS = "commerce-orders" - COMMERCE_PAYMENT_METHODS = "commerce-paymentMethods" - COMMERCE_PAYMENTS = "commerce-payments" - COMMERCE_PRODUCT_CATEGORIES = "commerce-productCategories" - COMMERCE_PRODUCTS = "commerce-products" - COMMERCE_TAX_COMPONENTS = "commerce-taxComponents" - COMMERCE_TRANSACTIONS = "commerce-transactions" + """ + Available data types + """ + + """ + allowed enum values + """ + ACCOUNT_TRANSACTIONS = 'accountTransactions' + BALANCE_SHEET = 'balanceSheet' + BANK_ACCOUNTS = 'bankAccounts' + BANK_TRANSACTIONS = 'bankTransactions' + BILL_CREDIT_NOTES = 'billCreditNotes' + BILL_PAYMENTS = 'billPayments' + BILLS = 'bills' + CASH_FLOW_STATEMENT = 'cashFlowStatement' + CHART_OF_ACCOUNTS = 'chartOfAccounts' + COMPANY = 'company' + CREDIT_NOTES = 'creditNotes' + CUSTOMERS = 'customers' + DIRECT_COSTS = 'directCosts' + DIRECT_INCOMES = 'directIncomes' + INVOICES = 'invoices' + ITEM_RECEIPTS = 'itemReceipts' + ITEMS = 'items' + JOURNAL_ENTRIES = 'journalEntries' + JOURNALS = 'journals' + PAYMENT_METHODS = 'paymentMethods' + PAYMENTS = 'payments' + PROFIT_AND_LOSS = 'profitAndLoss' + PURCHASE_ORDERS = 'purchaseOrders' + SALES_ORDERS = 'salesOrders' + SUPPLIERS = 'suppliers' + TAX_RATES = 'taxRates' + TRACKING_CATEGORIES = 'trackingCategories' + TRANSFERS = 'transfers' + BANKING_MINUS_ACCOUNT_BALANCES = 'banking-accountBalances' + BANKING_ACCOUNT_BALANCES = 'banking-accountBalances' + BANKING_MINUS_ACCOUNTS = 'banking-accounts' + BANKING_ACCOUNTS = 'banking-accounts' + BANKING_MINUS_TRANSACTION_CATEGORIES = 'banking-transactionCategories' + BANKING_TRANSACTION_CATEGORIES = 'banking-transactionCategories' + BANKING_MINUS_TRANSACTIONS = 'banking-transactions' + BANKING_TRANSACTIONS = 'banking-transactions' + COMMERCE_MINUS_COMPANY_INFO = 'commerce-companyInfo' + COMMERCE_COMPANY_INFO = 'commerce-companyInfo' + COMMERCE_MINUS_CUSTOMERS = 'commerce-customers' + COMMERCE_CUSTOMERS = 'commerce-customers' + COMMERCE_MINUS_DISPUTES = 'commerce-disputes' + COMMERCE_DISPUTES = 'commerce-disputes' + COMMERCE_MINUS_LOCATIONS = 'commerce-locations' + COMMERCE_LOCATIONS = 'commerce-locations' + COMMERCE_MINUS_ORDERS = 'commerce-orders' + COMMERCE_ORDERS = 'commerce-orders' + COMMERCE_MINUS_PAYMENT_METHODS = 'commerce-paymentMethods' + COMMERCE_PAYMENT_METHODS = 'commerce-paymentMethods' + COMMERCE_MINUS_PAYMENTS = 'commerce-payments' + COMMERCE_PAYMENTS = 'commerce-payments' + COMMERCE_MINUS_PRODUCT_CATEGORIES = 'commerce-productCategories' + COMMERCE_PRODUCT_CATEGORIES = 'commerce-productCategories' + COMMERCE_MINUS_PRODUCTS = 'commerce-products' + COMMERCE_PRODUCTS = 'commerce-products' + COMMERCE_MINUS_TAX_COMPONENTS = 'commerce-taxComponents' + COMMERCE_TAX_COMPONENTS = 'commerce-taxComponents' + COMMERCE_MINUS_TRANSACTIONS = 'commerce-transactions' + + COMMERCE_TRANSACTIONS = 'commerce-transactions' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of DataType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/platform/src/codat_platform/models/shared/datatypefeature.py b/platform/src/codat_platform/models/shared/datatypefeature.py index 18b60e23b..a606439d5 100644 --- a/platform/src/codat_platform/models/shared/datatypefeature.py +++ b/platform/src/codat_platform/models/shared/datatypefeature.py @@ -1,51 +1,121 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .datatype import DataType -from .supportedfeature import SupportedFeature, SupportedFeatureTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class DataTypeFeatureTypedDict(TypedDict): - r"""Describes support for a given datatype and associated operations""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - supported_features: List[SupportedFeatureTypedDict] - data_type: NotRequired[DataType] - r"""Available data types""" + Do not edit the class manually. +""" # noqa: E501 -class DataTypeFeature(BaseModel): - r"""Describes support for a given datatype and associated operations""" +from __future__ import annotations +from codat_platform.models.shared.datatype import DataType +import pprint +import re # noqa: F401 +import json - supported_features: Annotated[ - List[SupportedFeature], pydantic.Field(alias="supportedFeatures") - ] +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.supportedfeature import SupportedFeature, SupportedFeatureTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - data_type: Annotated[Optional[DataType], pydantic.Field(alias="dataType")] = None - r"""Available data types""" +class DataTypeFeature(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["dataType"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Describes support for a given datatype and associated operations + """ # noqa: E501 + data_type: Optional[DataType] = Field(default=None, description="Available data types", alias="dataType") + supported_features: List[SupportedFeature] = Field(alias="supportedFeatures") + __properties: ClassVar[List[str]] = ["dataType", "supportedFeatures"] + + @field_validator('data_type') + def data_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions']): + raise ValueError("must be one of enum values ('accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DataTypeFeature from a JSON string""" + return cls.from_dict(json.loads(json_str)) - return m + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: -try: - DataTypeFeature.model_rebuild() -except NameError: - pass + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in supported_features (list) + _items = [] + if self.supported_features: + for _item_supported_features in self.supported_features: + if _item_supported_features: + _items.append(_item_supported_features.to_dict()) + _dict['supportedFeatures'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DataTypeFeature from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "dataType": obj.get("dataType"), + "supportedFeatures": [SupportedFeature.from_dict(_item) for _item in obj["supportedFeatures"]] if obj.get("supportedFeatures") is not None else None + }) + return _obj + + + + + +class DataTypeFeatureTypedDict(TypedDict): + """TypedDict variant of DataTypeFeature, for dict-literal request/response inputs.""" + data_type: NotRequired[Optional[DataType]] + supported_features: NotRequired[List[SupportedFeatureTypedDict]] diff --git a/platform/src/codat_platform/models/shared/datatypereadsummary.py b/platform/src/codat_platform/models/shared/datatypereadsummary.py index 9ca055acd..7705f9bc7 100644 --- a/platform/src/codat_platform/models/shared/datatypereadsummary.py +++ b/platform/src/codat_platform/models/shared/datatypereadsummary.py @@ -1,82 +1,146 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .datatype import DataType -from .issue import Issue, IssueTypedDict -from .status import Status -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class DataTypeReadSummaryTypedDict(TypedDict): - connection_id: NotRequired[str] - r"""Unique identifier for a company's data connection.""" - data_type: NotRequired[DataType] - r"""Available data types""" - issues: NotRequired[Nullable[List[IssueTypedDict]]] - r"""A array of issues encountered during a data read.""" - records_modified: NotRequired[bool] - r"""`True` if records have been created, updated or deleted in Codat's cache.""" - status: NotRequired[Status] - r"""The current status of the dataset.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +from codat_platform.models.shared.status import Status +from codat_platform.models.shared.datatype import DataType +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.issue import Issue, IssueTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL class DataTypeReadSummary(BaseModel): - connection_id: Annotated[Optional[str], pydantic.Field(alias="connectionId")] = None - r"""Unique identifier for a company's data connection.""" - data_type: Annotated[Optional[DataType], pydantic.Field(alias="dataType")] = None - r"""Available data types""" + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'issues'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + DataTypeReadSummary + """ # noqa: E501 + connection_id: Optional[str] = Field(default=None, description="Unique identifier for a company's data connection.", alias="connectionId") + data_type: Optional[DataType] = Field(default=None, description="Available data types", alias="dataType") + records_modified: Optional[bool] = Field(default=None, description="`True` if records have been created, updated or deleted in Codat's cache.", alias="recordsModified") + status: Optional[Status] = Field(default=None, description="The current status of the dataset.") + issues: OptionalNullable[List[Issue]] = Field(default=UNSET, description="A array of issues encountered during a data read.") + __properties: ClassVar[List[str]] = ["connectionId", "dataType", "recordsModified", "status", "issues"] + + @field_validator('data_type') + def data_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value - issues: OptionalNullable[List[Issue]] = UNSET - r"""A array of issues encountered during a data read.""" + if value not in set(['accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions']): + raise ValueError("must be one of enum values ('accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions')") + return value - records_modified: Annotated[ - Optional[bool], pydantic.Field(alias="recordsModified") - ] = None - r"""`True` if records have been created, updated or deleted in Codat's cache.""" + @field_validator('status') + def status_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value - status: Optional[Status] = None - r"""The current status of the dataset.""" + if value not in set(['Initial', 'Queued', 'Fetching', 'MapQueued', 'Mapping', 'Complete', 'FetchError', 'MapError', 'InternalError', 'ProcessingQueued', 'Processing', 'ProcessingError', 'ValidationQueued', 'Validating', 'ValidationError', 'AuthError', 'Cancelled', 'NotSupported', 'RateLimitError', 'PermissionsError', 'PrerequisiteNotMet']): + raise ValueError("must be one of enum values ('Initial', 'Queued', 'Fetching', 'MapQueued', 'Mapping', 'Complete', 'FetchError', 'MapError', 'InternalError', 'ProcessingQueued', 'Processing', 'ProcessingError', 'ValidationQueued', 'Validating', 'ValidationError', 'AuthError', 'Cancelled', 'NotSupported', 'RateLimitError', 'PermissionsError', 'PrerequisiteNotMet')") + return value - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["connectionId", "dataType", "issues", "recordsModified", "status"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DataTypeReadSummary from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - nullable_fields = set(["issues"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - DataTypeReadSummary.model_rebuild() -except NameError: - pass + # override the default output from pydantic by calling `to_dict()` of each item in issues (list) + _items = [] + if self.issues: + for _item_issues in self.issues: + if _item_issues: + _items.append(_item_issues.to_dict()) + _dict['issues'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DataTypeReadSummary from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "connectionId": obj.get("connectionId"), + "dataType": obj.get("dataType"), + "recordsModified": obj.get("recordsModified"), + "status": obj.get("status"), + "issues": [Issue.from_dict(_item) for _item in obj["issues"]] if obj.get("issues") is not None else None + }) + return _obj + + + + + +class DataTypeReadSummaryTypedDict(TypedDict): + """TypedDict variant of DataTypeReadSummary, for dict-literal request/response inputs.""" + connection_id: NotRequired[Optional[str]] + data_type: NotRequired[Optional[DataType]] + records_modified: NotRequired[Optional[bool]] + status: NotRequired[Optional[Status]] + issues: NotRequired[Optional[List[IssueTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/datatypewritewebhook.py b/platform/src/codat_platform/models/shared/datatypewritewebhook.py index 6eb7da3e2..56cd6b660 100644 --- a/platform/src/codat_platform/models/shared/datatypewritewebhook.py +++ b/platform/src/codat_platform/models/shared/datatypewritewebhook.py @@ -1,97 +1,112 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .datatypewritewebhookpayload import ( - DataTypeWriteWebhookPayload, - DataTypeWriteWebhookPayloadTypedDict, -) -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class DataTypeWriteWebhookTypedDict(TypedDict): - event_type: NotRequired[str] - r"""The type of event.""" - generated_date: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.datatypewritewebhookpayload import DataTypeWriteWebhookPayload, DataTypeWriteWebhookPayloadTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` +class DataTypeWriteWebhook(BaseModel): - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} """ - id: NotRequired[str] - r"""Unique identifier of the event.""" - payload: NotRequired[DataTypeWriteWebhookPayloadTypedDict] + DataTypeWriteWebhook + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the event.") + event_type: Optional[str] = Field(default=None, description="The type of event.", alias="eventType") + generated_date: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="generatedDate") + payload: Optional[DataTypeWriteWebhookPayload] = None + __properties: ClassVar[List[str]] = ["id", "eventType", "generatedDate", "payload"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class DataTypeWriteWebhook(BaseModel): - event_type: Annotated[Optional[str], pydantic.Field(alias="eventType")] = None - r"""The type of event.""" - generated_date: Annotated[Optional[str], pydantic.Field(alias="generatedDate")] = ( - None - ) - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DataTypeWriteWebhook from a JSON string""" + return cls.from_dict(json.loads(json_str)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of payload + if self.payload: + _dict['payload'] = self.payload.to_dict() + return _dict - id: Optional[str] = None - r"""Unique identifier of the event.""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DataTypeWriteWebhook from a dict""" + if obj is None: + return None - payload: Optional[DataTypeWriteWebhookPayload] = None + if not isinstance(obj, dict): + return cls.model_validate(obj) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["eventType", "generatedDate", "id", "payload"]) - serialized = handler(self) - m = {} + _obj = cls.model_validate({ + "id": obj.get("id"), + "eventType": obj.get("eventType"), + "generatedDate": obj.get("generatedDate"), + "payload": DataTypeWriteWebhookPayload.from_dict(obj["payload"]) if obj.get("payload") is not None else None + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - DataTypeWriteWebhook.model_rebuild() -except NameError: - pass +class DataTypeWriteWebhookTypedDict(TypedDict): + """TypedDict variant of DataTypeWriteWebhook, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + event_type: NotRequired[Optional[str]] + generated_date: NotRequired[Optional[str]] + payload: NotRequired[Optional[DataTypeWriteWebhookPayloadTypedDict]] diff --git a/platform/src/codat_platform/models/shared/datatypewritewebhookpayload.py b/platform/src/codat_platform/models/shared/datatypewritewebhookpayload.py index 9aedccf94..272b0f877 100644 --- a/platform/src/codat_platform/models/shared/datatypewritewebhookpayload.py +++ b/platform/src/codat_platform/models/shared/datatypewritewebhookpayload.py @@ -1,194 +1,138 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from __future__ import annotations -from .companyreference import CompanyReference, CompanyReferenceTypedDict -from .datatypewritewebhookrecord import ( - DataTypeWriteWebhookRecord, - DataTypeWriteWebhookRecordTypedDict, -) -from .writestatus import WriteStatus -from .writetype import WriteType -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class DataTypeWriteWebhookPayloadTypedDict(TypedDict): - attachment_id: NotRequired[Nullable[str]] - r"""Unique identifier for the uploaded attachment, null if no attachment uploaded.""" - completed_on_date: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - connection_id: NotRequired[str] - r"""Unique identifier for a company's data connection.""" - id: NotRequired[str] - r"""Unique identifier of the write request. This is also known as the push operation ID.""" - record: NotRequired[DataTypeWriteWebhookRecordTypedDict] - reference_company: NotRequired[CompanyReferenceTypedDict] - requested_on_date: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` +# coding: utf-8 +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - status: NotRequired[WriteStatus] - r"""The current status of the write request, which is the same as the push operation status.""" - type: NotRequired[WriteType] - r"""Type of write request.""" + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.companyreference import CompanyReference, CompanyReferenceTypedDict +from codat_platform.models.shared.datatypewritewebhookrecord import DataTypeWriteWebhookRecord, DataTypeWriteWebhookRecordTypedDict +from codat_platform.models.shared.writestatus import WriteStatus +from codat_platform.models.shared.writetype import WriteType +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL class DataTypeWriteWebhookPayload(BaseModel): - attachment_id: Annotated[ - OptionalNullable[str], pydantic.Field(alias="attachmentId") - ] = UNSET - r"""Unique identifier for the uploaded attachment, null if no attachment uploaded.""" - - completed_on_date: Annotated[ - Optional[str], pydantic.Field(alias="completedOnDate") - ] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'attachmentId', 'attachment_id'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - - connection_id: Annotated[Optional[str], pydantic.Field(alias="connectionId")] = None - r"""Unique identifier for a company's data connection.""" - - id: Optional[str] = None - r"""Unique identifier of the write request. This is also known as the push operation ID.""" - + DataTypeWriteWebhookPayload + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the write request. This is also known as the push operation ID.") + type: Optional[WriteType] = None + reference_company: Optional[CompanyReference] = Field(default=None, alias="referenceCompany") + connection_id: Optional[str] = Field(default=None, description="Unique identifier for a company's data connection.", alias="connectionId") + requested_on_date: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="requestedOnDate") + completed_on_date: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="completedOnDate") + status: Optional[WriteStatus] = None record: Optional[DataTypeWriteWebhookRecord] = None + attachment_id: OptionalNullable[str] = Field(default=UNSET, description="Unique identifier for the uploaded attachment, null if no attachment uploaded.", alias="attachmentId") + __properties: ClassVar[List[str]] = ["id", "type", "referenceCompany", "connectionId", "requestedOnDate", "completedOnDate", "status", "record", "attachmentId"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DataTypeWriteWebhookPayload from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of reference_company + if self.reference_company: + _dict['referenceCompany'] = self.reference_company.to_dict() + # override the default output from pydantic by calling `to_dict()` of record + if self.record: + _dict['record'] = self.record.to_dict() + return _dict - reference_company: Annotated[ - Optional[CompanyReference], pydantic.Field(alias="referenceCompany") - ] = None - - requested_on_date: Annotated[ - Optional[str], pydantic.Field(alias="requestedOnDate") - ] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DataTypeWriteWebhookPayload from a dict""" + if obj is None: + return None + if not isinstance(obj, dict): + return cls.model_validate(obj) + _obj = cls.model_validate({ + "id": obj.get("id"), + "type": obj.get("type"), + "referenceCompany": CompanyReference.from_dict(obj["referenceCompany"]) if obj.get("referenceCompany") is not None else None, + "connectionId": obj.get("connectionId"), + "requestedOnDate": obj.get("requestedOnDate"), + "completedOnDate": obj.get("completedOnDate"), + "status": obj.get("status"), + "record": DataTypeWriteWebhookRecord.from_dict(obj["record"]) if obj.get("record") is not None else None, + "attachmentId": obj.get("attachmentId") + }) + return _obj - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - - status: Optional[WriteStatus] = None - r"""The current status of the write request, which is the same as the push operation status.""" - type: Optional[WriteType] = None - r"""Type of write request.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "attachmentId", - "completedOnDate", - "connectionId", - "id", - "record", - "referenceCompany", - "requestedOnDate", - "status", - "type", - ] - ) - nullable_fields = set(["attachmentId"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - DataTypeWriteWebhookPayload.model_rebuild() -except NameError: - pass +class DataTypeWriteWebhookPayloadTypedDict(TypedDict): + """TypedDict variant of DataTypeWriteWebhookPayload, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + type: NotRequired[Optional[WriteType]] + reference_company: NotRequired[Optional[CompanyReferenceTypedDict]] + connection_id: NotRequired[Optional[str]] + requested_on_date: NotRequired[Optional[str]] + completed_on_date: NotRequired[Optional[str]] + status: NotRequired[Optional[WriteStatus]] + record: NotRequired[Optional[DataTypeWriteWebhookRecordTypedDict]] + attachment_id: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/shared/datatypewritewebhookrecord.py b/platform/src/codat_platform/models/shared/datatypewritewebhookrecord.py index 18d438a6f..045ba3e90 100644 --- a/platform/src/codat_platform/models/shared/datatypewritewebhookrecord.py +++ b/platform/src/codat_platform/models/shared/datatypewritewebhookrecord.py @@ -1,33 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class DataTypeWriteWebhookRecordTypedDict(TypedDict): - id: NotRequired[str] - r"""The unique identifier of the data type created, updated, deleted, or had an attachment uploaded in the accounting platform.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class DataTypeWriteWebhookRecord(BaseModel): - id: Optional[str] = None - r"""The unique identifier of the data type created, updated, deleted, or had an attachment uploaded in the accounting platform.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["id"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + DataTypeWriteWebhookRecord + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="The unique identifier of the data type created, updated, deleted, or had an attachment uploaded in the accounting platform.") + __properties: ClassVar[List[str]] = ["id"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DataTypeWriteWebhookRecord from a JSON string""" + return cls.from_dict(json.loads(json_str)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - return m + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DataTypeWriteWebhookRecord from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id") + }) + return _obj + + + + + +class DataTypeWriteWebhookRecordTypedDict(TypedDict): + """TypedDict variant of DataTypeWriteWebhookRecord, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/shared/errormessage.py b/platform/src/codat_platform/models/shared/errormessage.py index 848815ba2..a05b34ec8 100644 --- a/platform/src/codat_platform/models/shared/errormessage.py +++ b/platform/src/codat_platform/models/shared/errormessage.py @@ -1,106 +1,126 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .errorvalidation import ErrorValidation, ErrorValidationTypedDict -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ErrorMessageTypedDict(TypedDict): - r"""Too many requests were made in a given amount of time. Wait a short period and then try again.""" - - can_be_retried: NotRequired[str] - r"""`True` if the error occurred transiently and can be retried.""" - correlation_id: NotRequired[str] - r"""Unique identifier used to propagate to all downstream services and determine the source of the error.""" - detailed_error_code: NotRequired[int] - r"""Machine readable error code used to automate processes based on the code returned.""" - error: NotRequired[str] - r"""A brief description of the error.""" - service: NotRequired[str] - r"""Codat's service the returned the error.""" - status_code: NotRequired[int] - r"""The HTTP status code returned by the error.""" - validation: NotRequired[Nullable[ErrorValidationTypedDict]] - r"""A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.errorvalidation import ErrorValidation, ErrorValidationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL class ErrorMessage(BaseModel): - r"""Too many requests were made in a given amount of time. Wait a short period and then try again.""" - can_be_retried: Annotated[Optional[str], pydantic.Field(alias="canBeRetried")] = ( - None + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'validation'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + ErrorMessage + """ # noqa: E501 + status_code: Optional[int] = Field(default=None, description="The HTTP status code returned by the error.", alias="statusCode") + service: Optional[str] = Field(default=None, description="Codat's service the returned the error.") + error: Optional[str] = Field(default=None, description="A brief description of the error.") + correlation_id: Optional[str] = Field(default=None, description="Unique identifier used to propagate to all downstream services and determine the source of the error.", alias="correlationId") + validation: OptionalNullable[ErrorValidation] = UNSET + can_be_retried: Optional[str] = Field(default=None, description="`True` if the error occurred transiently and can be retried.", alias="canBeRetried") + detailed_error_code: Optional[int] = Field(default=None, description="Machine readable error code used to automate processes based on the code returned.", alias="detailedErrorCode") + __properties: ClassVar[List[str]] = ["statusCode", "service", "error", "correlationId", "validation", "canBeRetried", "detailedErrorCode"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), ) - r"""`True` if the error occurred transiently and can be retried.""" - correlation_id: Annotated[Optional[str], pydantic.Field(alias="correlationId")] = ( - None - ) - r"""Unique identifier used to propagate to all downstream services and determine the source of the error.""" - detailed_error_code: Annotated[ - Optional[int], pydantic.Field(alias="detailedErrorCode") - ] = None - r"""Machine readable error code used to automate processes based on the code returned.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - error: Optional[str] = None - r"""A brief description of the error.""" + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - service: Optional[str] = None - r"""Codat's service the returned the error.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ErrorMessage from a JSON string""" + return cls.from_dict(json.loads(json_str)) - status_code: Annotated[Optional[int], pydantic.Field(alias="statusCode")] = None - r"""The HTTP status code returned by the error.""" + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - validation: OptionalNullable[ErrorValidation] = UNSET - r"""A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here.""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "canBeRetried", - "correlationId", - "detailedErrorCode", - "error", - "service", - "statusCode", - "validation", - ] + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - nullable_fields = set(["validation"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - ErrorMessage.model_rebuild() -except NameError: - pass + # override the default output from pydantic by calling `to_dict()` of validation + if self.validation: + _dict['validation'] = self.validation.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ErrorMessage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "statusCode": obj.get("statusCode"), + "service": obj.get("service"), + "error": obj.get("error"), + "correlationId": obj.get("correlationId"), + "validation": ErrorValidation.from_dict(obj["validation"]) if obj.get("validation") is not None else None, + "canBeRetried": obj.get("canBeRetried"), + "detailedErrorCode": obj.get("detailedErrorCode") + }) + return _obj + + + + + +class ErrorMessageTypedDict(TypedDict): + """TypedDict variant of ErrorMessage, for dict-literal request/response inputs.""" + status_code: NotRequired[Optional[int]] + service: NotRequired[Optional[str]] + error: NotRequired[Optional[str]] + correlation_id: NotRequired[Optional[str]] + validation: NotRequired[Optional[ErrorValidationTypedDict]] + can_be_retried: NotRequired[Optional[str]] + detailed_error_code: NotRequired[Optional[int]] diff --git a/platform/src/codat_platform/models/shared/errorvalidation.py b/platform/src/codat_platform/models/shared/errorvalidation.py index 9e01b317e..ffd474251 100644 --- a/platform/src/codat_platform/models/shared/errorvalidation.py +++ b/platform/src/codat_platform/models/shared/errorvalidation.py @@ -1,54 +1,122 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .errorvalidationitem import ErrorValidationItem, ErrorValidationItemTypedDict -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from pydantic import model_serializer -from typing import List -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ErrorValidationTypedDict(TypedDict): - r"""A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - errors: NotRequired[Nullable[List[ErrorValidationItemTypedDict]]] - warnings: NotRequired[Nullable[List[ErrorValidationItemTypedDict]]] + Do not edit the class manually. +""" # noqa: E501 -class ErrorValidation(BaseModel): - r"""A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - errors: OptionalNullable[List[ErrorValidationItem]] = UNSET +from pydantic import BaseModel, ConfigDict, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.errorvalidationitem import ErrorValidationItem, ErrorValidationItemTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - warnings: OptionalNullable[List[ErrorValidationItem]] = UNSET +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL +class ErrorValidation(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["errors", "warnings"]) - nullable_fields = set(["errors", "warnings"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m + _nullable = {'errors', 'warnings'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here. + """ # noqa: E501 + errors: OptionalNullable[List[ErrorValidationItem]] = UNSET + warnings: OptionalNullable[List[ErrorValidationItem]] = UNSET + __properties: ClassVar[List[str]] = ["errors", "warnings"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ErrorValidation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in errors (list) + _items = [] + if self.errors: + for _item_errors in self.errors: + if _item_errors: + _items.append(_item_errors.to_dict()) + _dict['errors'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in warnings (list) + _items = [] + if self.warnings: + for _item_warnings in self.warnings: + if _item_warnings: + _items.append(_item_warnings.to_dict()) + _dict['warnings'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ErrorValidation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "errors": [ErrorValidationItem.from_dict(_item) for _item in obj["errors"]] if obj.get("errors") is not None else None, + "warnings": [ErrorValidationItem.from_dict(_item) for _item in obj["warnings"]] if obj.get("warnings") is not None else None + }) + return _obj + + + + + +class ErrorValidationTypedDict(TypedDict): + """TypedDict variant of ErrorValidation, for dict-literal request/response inputs.""" + errors: NotRequired[Optional[List[ErrorValidationItemTypedDict]]] + warnings: NotRequired[Optional[List[ErrorValidationItemTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/errorvalidationitem.py b/platform/src/codat_platform/models/shared/errorvalidationitem.py index 1934ed738..7f6ba0546 100644 --- a/platform/src/codat_platform/models/shared/errorvalidationitem.py +++ b/platform/src/codat_platform/models/shared/errorvalidationitem.py @@ -1,66 +1,110 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ErrorValidationItemTypedDict(TypedDict): - item_id: NotRequired[Nullable[str]] - r"""Unique identifier for a validation item.""" - message: NotRequired[Nullable[str]] - r"""A message outlining validation item's issue.""" - validator_name: NotRequired[Nullable[str]] - r"""Name of validator.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class ErrorValidationItem(BaseModel): - item_id: Annotated[OptionalNullable[str], pydantic.Field(alias="itemId")] = UNSET - r"""Unique identifier for a validation item.""" - message: OptionalNullable[str] = UNSET - r"""A message outlining validation item's issue.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - validator_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="validatorName") - ] = UNSET - r"""Name of validator.""" +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL +class ErrorValidationItem(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["itemId", "message", "validatorName"]) - nullable_fields = set(["itemId", "message", "validatorName"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - ErrorValidationItem.model_rebuild() -except NameError: - pass + _nullable = {'itemId', 'item_id', 'message', 'validatorName', 'validator_name'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + ErrorValidationItem + """ # noqa: E501 + item_id: OptionalNullable[str] = Field(default=UNSET, description="Unique identifier for a validation item.", alias="itemId") + message: OptionalNullable[str] = Field(default=UNSET, description="A message outlining validation item's issue.") + validator_name: OptionalNullable[str] = Field(default=UNSET, description="Name of validator.", alias="validatorName") + __properties: ClassVar[List[str]] = ["itemId", "message", "validatorName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ErrorValidationItem from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ErrorValidationItem from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "itemId": obj.get("itemId"), + "message": obj.get("message"), + "validatorName": obj.get("validatorName") + }) + return _obj + + + + + +class ErrorValidationItemTypedDict(TypedDict): + """TypedDict variant of ErrorValidationItem, for dict-literal request/response inputs.""" + item_id: NotRequired[Optional[str]] + message: NotRequired[Optional[str]] + validator_name: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/shared/featurestate.py b/platform/src/codat_platform/models/shared/featurestate.py index 27b65913f..39392e1f8 100644 --- a/platform/src/codat_platform/models/shared/featurestate.py +++ b/platform/src/codat_platform/models/shared/featurestate.py @@ -1,15 +1,41 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class FeatureState(str, Enum): - r"""The current release state of the feature.""" - - RELEASE = "Release" - ALPHA = "Alpha" - BETA = "Beta" - DEPRECATED = "Deprecated" - NOT_SUPPORTED = "NotSupported" - NOT_IMPLEMENTED = "NotImplemented" + """ + The current release state of the feature. + """ + + """ + allowed enum values + """ + RELEASE = 'Release' + ALPHA = 'Alpha' + BETA = 'Beta' + DEPRECATED = 'Deprecated' + NOT_SUPPORTED = 'NotSupported' + NOT_IMPLEMENTED = 'NotImplemented' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of FeatureState from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/platform/src/codat_platform/models/shared/featuretype.py b/platform/src/codat_platform/models/shared/featuretype.py index f0c620a36..036c9f319 100644 --- a/platform/src/codat_platform/models/shared/featuretype.py +++ b/platform/src/codat_platform/models/shared/featuretype.py @@ -1,19 +1,45 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class FeatureType(str, Enum): - r"""The type of feature.""" - - GET = "Get" - POST = "Post" - CATEGORIZATION = "Categorization" - DELETE = "Delete" - PUT = "Put" - GET_AS_PDF = "GetAsPdf" - DOWNLOAD_ATTACHMENT = "DownloadAttachment" - GET_ATTACHMENT = "GetAttachment" - GET_ATTACHMENTS = "GetAttachments" - UPLOAD_ATTACHMENT = "UploadAttachment" + """ + The type of feature. + """ + + """ + allowed enum values + """ + GET = 'Get' + POST = 'Post' + CATEGORIZATION = 'Categorization' + DELETE = 'Delete' + PUT = 'Put' + GET_AS_PDF = 'GetAsPdf' + DOWNLOAD_ATTACHMENT = 'DownloadAttachment' + GET_ATTACHMENT = 'GetAttachment' + GET_ATTACHMENTS = 'GetAttachments' + UPLOAD_ATTACHMENT = 'UploadAttachment' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of FeatureType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/platform/src/codat_platform/models/shared/halref.py b/platform/src/codat_platform/models/shared/halref.py index e3b0a3629..b12045576 100644 --- a/platform/src/codat_platform/models/shared/halref.py +++ b/platform/src/codat_platform/models/shared/halref.py @@ -1,33 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class HalRefTypedDict(TypedDict): - href: NotRequired[str] - r"""Uri hypertext reference.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class HalRef(BaseModel): - href: Optional[str] = None - r"""Uri hypertext reference.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["href"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + HalRef + """ # noqa: E501 + href: Optional[str] = Field(default=None, description="Uri hypertext reference.") + __properties: ClassVar[List[str]] = ["href"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HalRef from a JSON string""" + return cls.from_dict(json.loads(json_str)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - return m + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HalRef from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "href": obj.get("href") + }) + return _obj + + + + + +class HalRefTypedDict(TypedDict): + """TypedDict variant of HalRef, for dict-literal request/response inputs.""" + href: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/shared/imagereference.py b/platform/src/codat_platform/models/shared/imagereference.py index 2dabc4e26..3d17e9526 100644 --- a/platform/src/codat_platform/models/shared/imagereference.py +++ b/platform/src/codat_platform/models/shared/imagereference.py @@ -1,42 +1,102 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ImageReferenceTypedDict(TypedDict): - r"""Image reference.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - alt: NotRequired[str] - r"""Alternative text when image is not available.""" - src: NotRequired[str] - r"""Source URL for image.""" + Do not edit the class manually. +""" # noqa: E501 -class ImageReference(BaseModel): - r"""Image reference.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - alt: Optional[str] = None - r"""Alternative text when image is not available.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - src: Optional[str] = None - r"""Source URL for image.""" +class ImageReference(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["alt", "src"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Image reference. + """ # noqa: E501 + src: Optional[str] = Field(default=None, description="Source URL for image.") + alt: Optional[str] = Field(default=None, description="Alternative text when image is not available.") + __properties: ClassVar[List[str]] = ["src", "alt"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ImageReference from a JSON string""" + return cls.from_dict(json.loads(json_str)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - return m + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ImageReference from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "src": obj.get("src"), + "alt": obj.get("alt") + }) + return _obj + + + + + +class ImageReferenceTypedDict(TypedDict): + """TypedDict variant of ImageReference, for dict-literal request/response inputs.""" + src: NotRequired[Optional[str]] + alt: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/shared/integration.py b/platform/src/codat_platform/models/shared/integration.py index 3d7a786c4..41668e58c 100644 --- a/platform/src/codat_platform/models/shared/integration.py +++ b/platform/src/codat_platform/models/shared/integration.py @@ -1,114 +1,146 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .datatypefeature import DataTypeFeature, DataTypeFeatureTypedDict -from .sourcetype import SourceType -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class IntegrationTypedDict(TypedDict): - r"""An integration that Codat supports""" - - enabled: bool - r"""Whether this integration is enabled for your customers to use.""" - key: str - r"""A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys.""" - logo_url: str - r"""Static url for integration's logo.""" - name: str - r"""Name of integration.""" - data_provided_by: NotRequired[str] - r"""The name of the data provider.""" - datatype_features: NotRequired[List[DataTypeFeatureTypedDict]] - integration_id: NotRequired[str] - r"""A Codat ID representing the integration.""" - is_beta: NotRequired[bool] - r"""`True` if the integration is currently in beta release.""" - is_offline_connector: NotRequired[bool] - r"""`True` if the integration is to an application installed and run locally on an SMBs computer.""" - source_id: NotRequired[str] - r"""A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`.""" - source_type: NotRequired[SourceType] - r"""The type of platform of the connection.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class Integration(BaseModel): - r"""An integration that Codat supports""" - enabled: bool - r"""Whether this integration is enabled for your customers to use.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - key: str - r"""A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys.""" +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.datatypefeature import DataTypeFeature, DataTypeFeatureTypedDict +from codat_platform.models.shared.sourcetype import SourceType +from typing import Optional, Set +from typing_extensions import Self - logo_url: Annotated[str, pydantic.Field(alias="logoUrl")] - r"""Static url for integration's logo.""" +class Integration(BaseModel): - name: str - r"""Name of integration.""" + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + An integration that Codat supports + """ # noqa: E501 + key: str = Field(description="A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys.") + logo_url: str = Field(description="Static url for integration's logo.", alias="logoUrl") + name: str = Field(description="Name of integration.") + enabled: bool = Field(description="Whether this integration is enabled for your customers to use.") + source_id: Optional[str] = Field(default=None, description="A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`.", alias="sourceId") + source_type: Optional[SourceType] = Field(default=None, alias="sourceType") + integration_id: Optional[str] = Field(default=None, description="A Codat ID representing the integration.", alias="integrationId") + is_offline_connector: Optional[bool] = Field(default=None, description="`True` if the integration is to an application installed and run locally on an SMBs computer.", alias="isOfflineConnector") + is_beta: Optional[bool] = Field(default=None, description="`True` if the integration is currently in beta release.", alias="isBeta") + data_provided_by: Optional[str] = Field(default=None, description="The name of the data provider.", alias="dataProvidedBy") + datatype_features: Optional[List[DataTypeFeature]] = Field(default=None, alias="datatypeFeatures") + __properties: ClassVar[List[str]] = ["key", "logoUrl", "name", "enabled", "sourceId", "sourceType", "integrationId", "isOfflineConnector", "isBeta", "dataProvidedBy", "datatypeFeatures"] + + @field_validator('key') + def key_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"[a-z]{4}", value): + raise ValueError(r"must validate the regular expression /[a-z]{4}/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - data_provided_by: Annotated[ - Optional[str], pydantic.Field(alias="dataProvidedBy") - ] = None - r"""The name of the data provider.""" - datatype_features: Annotated[ - Optional[List[DataTypeFeature]], pydantic.Field(alias="datatypeFeatures") - ] = None + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - integration_id: Annotated[Optional[str], pydantic.Field(alias="integrationId")] = ( - None - ) - r"""A Codat ID representing the integration.""" + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - is_beta: Annotated[Optional[bool], pydantic.Field(alias="isBeta")] = None - r"""`True` if the integration is currently in beta release.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Integration from a JSON string""" + return cls.from_dict(json.loads(json_str)) - is_offline_connector: Annotated[ - Optional[bool], pydantic.Field(alias="isOfflineConnector") - ] = None - r"""`True` if the integration is to an application installed and run locally on an SMBs computer.""" + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - source_id: Annotated[Optional[str], pydantic.Field(alias="sourceId")] = None - r"""A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`.""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - source_type: Annotated[Optional[SourceType], pydantic.Field(alias="sourceType")] = ( - None - ) - r"""The type of platform of the connection.""" + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "dataProvidedBy", - "datatypeFeatures", - "integrationId", - "isBeta", - "isOfflineConnector", - "sourceId", - "sourceType", - ] + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - serialized = handler(self) - m = {} + # override the default output from pydantic by calling `to_dict()` of each item in datatype_features (list) + _items = [] + if self.datatype_features: + for _item_datatype_features in self.datatype_features: + if _item_datatype_features: + _items.append(_item_datatype_features.to_dict()) + _dict['datatypeFeatures'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Integration from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "key": obj.get("key"), + "logoUrl": obj.get("logoUrl"), + "name": obj.get("name"), + "enabled": obj.get("enabled"), + "sourceId": obj.get("sourceId"), + "sourceType": obj.get("sourceType"), + "integrationId": obj.get("integrationId"), + "isOfflineConnector": obj.get("isOfflineConnector"), + "isBeta": obj.get("isBeta"), + "dataProvidedBy": obj.get("dataProvidedBy"), + "datatypeFeatures": [DataTypeFeature.from_dict(_item) for _item in obj["datatypeFeatures"]] if obj.get("datatypeFeatures") is not None else None + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - Integration.model_rebuild() -except NameError: - pass +class IntegrationTypedDict(TypedDict): + """TypedDict variant of Integration, for dict-literal request/response inputs.""" + key: NotRequired[str] + logo_url: NotRequired[str] + name: NotRequired[str] + enabled: NotRequired[bool] + source_id: NotRequired[Optional[str]] + source_type: NotRequired[Optional[SourceType]] + integration_id: NotRequired[Optional[str]] + is_offline_connector: NotRequired[Optional[bool]] + is_beta: NotRequired[Optional[bool]] + data_provided_by: NotRequired[Optional[str]] + datatype_features: NotRequired[Optional[List[DataTypeFeatureTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/integrations.py b/platform/src/codat_platform/models/shared/integrations.py index 9b36dcb26..0516c275d 100644 --- a/platform/src/codat_platform/models/shared/integrations.py +++ b/platform/src/codat_platform/models/shared/integrations.py @@ -1,58 +1,124 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .integration import Integration, IntegrationTypedDict -from .links import Links, LinksTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.integration import Integration, IntegrationTypedDict +from codat_platform.models.shared.links import Links, LinksTypedDict +from typing import Optional, Set +from typing_extensions import Self +class Integrations(BaseModel): -class IntegrationsTypedDict(TypedDict): - links: LinksTypedDict - page_number: int - r"""Current page number.""" - page_size: int - r"""Number of items to return in results array.""" - total_results: int - r"""Total number of items.""" - results: NotRequired[List[IntegrationTypedDict]] + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + Integrations + """ # noqa: E501 + page_number: int = Field(description="Current page number.", alias="pageNumber") + page_size: int = Field(description="Number of items to return in results array.", alias="pageSize") + total_results: int = Field(description="Total number of items.", alias="totalResults") + links: Links = Field(alias="_links") + results: Optional[List[Integration]] = None + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links", "results"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class Integrations(BaseModel): - links: Annotated[Links, pydantic.Field(alias="_links")] - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Integrations from a JSON string""" + return cls.from_dict(json.loads(json_str)) - results: Optional[List[Integration]] = None + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["results"]) - serialized = handler(self) - m = {} + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['_links'] = self.links.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + return _dict - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Integrations from a dict""" + if obj is None: + return None - return m + if not isinstance(obj, dict): + return cls.model_validate(obj) + _obj = cls.model_validate({ + "pageNumber": obj.get("pageNumber"), + "pageSize": obj.get("pageSize"), + "totalResults": obj.get("totalResults"), + "_links": Links.from_dict(obj["_links"]) if obj.get("_links") is not None else None, + "results": [Integration.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj -try: - Integrations.model_rebuild() -except NameError: - pass + + + + +class IntegrationsTypedDict(TypedDict): + """TypedDict variant of Integrations, for dict-literal request/response inputs.""" + page_number: NotRequired[int] + page_size: NotRequired[int] + total_results: NotRequired[int] + links: NotRequired[LinksTypedDict] + results: NotRequired[Optional[List[IntegrationTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/issue.py b/platform/src/codat_platform/models/shared/issue.py index 53cff7d7c..e6a608f7e 100644 --- a/platform/src/codat_platform/models/shared/issue.py +++ b/platform/src/codat_platform/models/shared/issue.py @@ -1,88 +1,109 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) -class IssueLinksTypedDict(TypedDict): - logs: NotRequired[str] - r"""A link to the validation logs, providing details on any errors or warnings encountered.""" - portal: NotRequired[str] - r"""A link to the company's past data read history in the Codat portal.""" - read_more: NotRequired[str] - r"""A link to Codat's documentation with additional information on how to troubleshoot this issue.""" + Do not edit the class manually. +""" # noqa: E501 -class IssueLinks(BaseModel): - logs: Optional[str] = None - r"""A link to the validation logs, providing details on any errors or warnings encountered.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - portal: Optional[str] = None - r"""A link to the company's past data read history in the Codat portal.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.issue_links import IssueLinks, IssueLinksTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - read_more: Annotated[Optional[str], pydantic.Field(alias="readMore")] = None - r"""A link to Codat's documentation with additional information on how to troubleshoot this issue.""" +class Issue(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["logs", "portal", "readMore"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Details of a problem encountered during a data read. + """ # noqa: E501 + type: Optional[str] = Field(default=None, description="The type of issue.") + message: Optional[str] = Field(default=None, description="A message describing the issue.") + links: Optional[IssueLinks] = None + __properties: ClassVar[List[str]] = ["type", "message", "links"] - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) -class IssueTypedDict(TypedDict): - r"""Details of a problem encountered during a data read.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Issue from a JSON string""" + return cls.from_dict(json.loads(json_str)) - links: NotRequired[IssueLinksTypedDict] - message: NotRequired[str] - r"""A message describing the issue.""" - type: NotRequired[str] - r"""The type of issue.""" + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: -class Issue(BaseModel): - r"""Details of a problem encountered during a data read.""" + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - links: Optional[IssueLinks] = None + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['links'] = self.links.to_dict() + return _dict - message: Optional[str] = None - r"""A message describing the issue.""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Issue from a dict""" + if obj is None: + return None - type: Optional[str] = None - r"""The type of issue.""" + if not isinstance(obj, dict): + return cls.model_validate(obj) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["links", "message", "type"]) - serialized = handler(self) - m = {} + _obj = cls.model_validate({ + "type": obj.get("type"), + "message": obj.get("message"), + "links": IssueLinks.from_dict(obj["links"]) if obj.get("links") is not None else None + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - IssueLinks.model_rebuild() -except NameError: - pass +class IssueTypedDict(TypedDict): + """TypedDict variant of Issue, for dict-literal request/response inputs.""" + type: NotRequired[Optional[str]] + message: NotRequired[Optional[str]] + links: NotRequired[Optional[IssueLinksTypedDict]] diff --git a/platform/src/codat_platform/models/shared/links.py b/platform/src/codat_platform/models/shared/links.py index 652c44d57..7006ec78b 100644 --- a/platform/src/codat_platform/models/shared/links.py +++ b/platform/src/codat_platform/models/shared/links.py @@ -1,48 +1,121 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .halref import HalRef, HalRefTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class LinksTypedDict(TypedDict): - current: HalRefTypedDict - self_: HalRefTypedDict - next: NotRequired[HalRefTypedDict] - previous: NotRequired[HalRefTypedDict] + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class Links(BaseModel): - current: HalRef - self_: Annotated[HalRef, pydantic.Field(alias="self")] +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - next: Optional[HalRef] = None +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.halref import HalRef, HalRefTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - previous: Optional[HalRef] = None +class Links(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["next", "previous"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Links + """ # noqa: E501 + self_: HalRef = Field(alias="self") + current: HalRef + next: Optional[HalRef] = None + previous: Optional[HalRef] = None + __properties: ClassVar[List[str]] = ["self", "current", "next", "previous"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - return m + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Links from a JSON string""" + return cls.from_dict(json.loads(json_str)) -try: - Links.model_rebuild() -except NameError: - pass + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of var_self + if self.self_: + _dict['self'] = self.self_.to_dict() + # override the default output from pydantic by calling `to_dict()` of current + if self.current: + _dict['current'] = self.current.to_dict() + # override the default output from pydantic by calling `to_dict()` of next + if self.next: + _dict['next'] = self.next.to_dict() + # override the default output from pydantic by calling `to_dict()` of previous + if self.previous: + _dict['previous'] = self.previous.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Links from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "self": HalRef.from_dict(obj["self"]) if obj.get("self") is not None else None, + "current": HalRef.from_dict(obj["current"]) if obj.get("current") is not None else None, + "next": HalRef.from_dict(obj["next"]) if obj.get("next") is not None else None, + "previous": HalRef.from_dict(obj["previous"]) if obj.get("previous") is not None else None + }) + return _obj + + + + + +class LinksTypedDict(TypedDict): + """TypedDict variant of Links, for dict-literal request/response inputs.""" + self_: NotRequired[HalRefTypedDict] + current: HalRefTypedDict + next: NotRequired[Optional[HalRefTypedDict]] + previous: NotRequired[Optional[HalRefTypedDict]] diff --git a/platform/src/codat_platform/models/shared/profile.py b/platform/src/codat_platform/models/shared/profile.py index d85c8aace..3a534b08d 100644 --- a/platform/src/codat_platform/models/shared/profile.py +++ b/platform/src/codat_platform/models/shared/profile.py @@ -1,90 +1,117 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ProfileTypedDict(TypedDict): - r"""Describes your Codat client instance""" - - name: str - r"""The name given to the instance.""" - redirect_url: str - r"""The redirect URL pasted on to the SMB once Codat's [Hosted Link](https://docs.codat.io/auth-flow/authorize-hosted-link) has been completed by the SMB.""" - api_key: NotRequired[str] - r"""The API key for this Codat instance.""" - confirm_company_name: NotRequired[bool] - r"""`True` if the company name has been confirmed.""" - icon_url: NotRequired[str] - r"""Static url to your organization's icon.""" - logo_url: NotRequired[str] - r"""Static url to your organization's logo.""" - white_list_urls: NotRequired[List[str]] - r"""A list of urls that are allowed to communicate with Codat. If empty any url is allowed to communicate with Codat.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class Profile(BaseModel): - r"""Describes your Codat client instance""" - - name: str - r"""The name given to the instance.""" - - redirect_url: Annotated[str, pydantic.Field(alias="redirectUrl")] - r"""The redirect URL pasted on to the SMB once Codat's [Hosted Link](https://docs.codat.io/auth-flow/authorize-hosted-link) has been completed by the SMB.""" - - api_key: Annotated[ - Optional[str], - pydantic.Field( - deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible.", - alias="apiKey", - ), - ] = None - r"""The API key for this Codat instance.""" - - confirm_company_name: Annotated[ - Optional[bool], - pydantic.Field( - deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible.", - alias="confirmCompanyName", - ), - ] = None - r"""`True` if the company name has been confirmed.""" - - icon_url: Annotated[Optional[str], pydantic.Field(alias="iconUrl")] = None - r"""Static url to your organization's icon.""" - - logo_url: Annotated[Optional[str], pydantic.Field(alias="logoUrl")] = None - r"""Static url to your organization's logo.""" - - white_list_urls: Annotated[ - Optional[List[str]], pydantic.Field(alias="whiteListUrls") - ] = None - r"""A list of urls that are allowed to communicate with Codat. If empty any url is allowed to communicate with Codat.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["apiKey", "confirmCompanyName", "iconUrl", "logoUrl", "whiteListUrls"] - ) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Describes your Codat client instance + """ # noqa: E501 + name: str = Field(description="The name given to the instance.") + logo_url: Optional[str] = Field(default=None, description="Static url to your organization's logo.", alias="logoUrl") + icon_url: Optional[str] = Field(default=None, description="Static url to your organization's icon.", alias="iconUrl") + redirect_url: str = Field(description="The redirect URL pasted on to the SMB once Codat's [Hosted Link](https://docs.codat.io/auth-flow/authorize-hosted-link) has been completed by the SMB.", alias="redirectUrl") + white_list_urls: Optional[List[str]] = Field(default=None, description="A list of urls that are allowed to communicate with Codat. If empty any url is allowed to communicate with Codat.", alias="whiteListUrls") + api_key: Optional[str] = Field(default=None, description="The API key for this Codat instance.", alias="apiKey") + confirm_company_name: Optional[bool] = Field(default=None, description="`True` if the company name has been confirmed.", alias="confirmCompanyName") + __properties: ClassVar[List[str]] = ["name", "logoUrl", "iconUrl", "redirectUrl", "whiteListUrls", "apiKey", "confirmCompanyName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Profile from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Profile from a dict""" + if obj is None: + return None - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + if not isinstance(obj, dict): + return cls.model_validate(obj) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + _obj = cls.model_validate({ + "name": obj.get("name"), + "logoUrl": obj.get("logoUrl"), + "iconUrl": obj.get("iconUrl"), + "redirectUrl": obj.get("redirectUrl"), + "whiteListUrls": obj.get("whiteListUrls"), + "apiKey": obj.get("apiKey"), + "confirmCompanyName": obj.get("confirmCompanyName") + }) + return _obj - return m -try: - Profile.model_rebuild() -except NameError: - pass + + +class ProfileTypedDict(TypedDict): + """TypedDict variant of Profile, for dict-literal request/response inputs.""" + name: NotRequired[str] + logo_url: NotRequired[Optional[str]] + icon_url: NotRequired[Optional[str]] + redirect_url: NotRequired[str] + white_list_urls: NotRequired[Optional[List[str]]] + api_key: NotRequired[Optional[str]] + confirm_company_name: NotRequired[Optional[bool]] diff --git a/platform/src/codat_platform/models/shared/pulloperation.py b/platform/src/codat_platform/models/shared/pulloperation.py index c70b8a497..2c2173d3f 100644 --- a/platform/src/codat_platform/models/shared/pulloperation.py +++ b/platform/src/codat_platform/models/shared/pulloperation.py @@ -1,225 +1,145 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from enum import Enum -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class DatasetStatus(str, Enum): - r"""The current status of the dataset.""" - - INITIAL = "Initial" - QUEUED = "Queued" - FETCHING = "Fetching" - MAP_QUEUED = "MapQueued" - MAPPING = "Mapping" - COMPLETE = "Complete" - FETCH_ERROR = "FetchError" - MAP_ERROR = "MapError" - INTERNAL_ERROR = "InternalError" - PROCESSING_QUEUED = "ProcessingQueued" - PROCESSING = "Processing" - PROCESSING_ERROR = "ProcessingError" - VALIDATION_QUEUED = "ValidationQueued" - VALIDATING = "Validating" - VALIDATION_ERROR = "ValidationError" - AUTH_ERROR = "AuthError" - CANCELLED = "Cancelled" - NOT_SUPPORTED = "NotSupported" - RATE_LIMIT_ERROR = "RateLimitError" - PERMISSIONS_ERROR = "PermissionsError" - PREREQUISITE_NOT_MET = "PrerequisiteNotMet" +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class PullOperationTypedDict(TypedDict): - r"""Information about a queued, in progress or completed pull operation. - *Formally called `dataset`* - """ - - company_id: str - r"""Unique identifier of the company associated to this pull operation.""" - connection_id: str - r"""Unique identifier of the connection associated to this pull operation.""" - data_type: str - r"""The data type you are requesting in a pull operation.""" - id: str - r"""Unique identifier of the pull operation.""" - is_completed: bool - r"""`True` if the pull operation is completed successfully. The `isCompleted` property is not queryable. To filter failed pull operations, query by `status!=Complete&&status!=NotSupported` instead.""" - is_errored: bool - r"""`True` if the pull operation entered an error state.""" - progress: int - r"""An integer signifying the progress of the pull operation.""" - requested: str - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - status: DatasetStatus - r"""The current status of the dataset.""" - completed: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from codat_platform.models.dataset_status import DatasetStatus +import pprint +import re # noqa: F401 +import json - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - error_message: NotRequired[Nullable[str]] - r"""A message about a transient or persistent error returned by Codat or the source platform.""" - status_description: NotRequired[Nullable[str]] - r"""Additional information about the dataset status.""" - +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL class PullOperation(BaseModel): - r"""Information about a queued, in progress or completed pull operation. - *Formally called `dataset`* - """ - - company_id: Annotated[str, pydantic.Field(alias="companyId")] - r"""Unique identifier of the company associated to this pull operation.""" - - connection_id: Annotated[str, pydantic.Field(alias="connectionId")] - r"""Unique identifier of the connection associated to this pull operation.""" - - data_type: Annotated[str, pydantic.Field(alias="dataType")] - r"""The data type you are requesting in a pull operation.""" - - id: str - r"""Unique identifier of the pull operation.""" - - is_completed: Annotated[bool, pydantic.Field(alias="isCompleted")] - r"""`True` if the pull operation is completed successfully. The `isCompleted` property is not queryable. To filter failed pull operations, query by `status!=Complete&&status!=NotSupported` instead.""" - - is_errored: Annotated[bool, pydantic.Field(alias="isErrored")] - r"""`True` if the pull operation entered an error state.""" - - progress: int - r"""An integer signifying the progress of the pull operation.""" - requested: str - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'errorMessage', 'error_message', 'statusDescription', 'status_description'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ + Information about a queued, in progress or completed pull operation. *Formally called `dataset`* + """ # noqa: E501 + id: str = Field(description="Unique identifier of the pull operation.") + company_id: str = Field(description="Unique identifier of the company associated to this pull operation.", alias="companyId") + connection_id: str = Field(description="Unique identifier of the connection associated to this pull operation.", alias="connectionId") + data_type: str = Field(description="The data type you are requesting in a pull operation.", alias="dataType") + status: DatasetStatus = Field(description="The current status of the dataset.") + status_description: OptionalNullable[str] = Field(default=UNSET, description="Additional information about the dataset status.", alias="statusDescription") + error_message: OptionalNullable[str] = Field(default=UNSET, description="A message about a transient or persistent error returned by Codat or the source platform.", alias="errorMessage") + requested: str = Field(description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.") + completed: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.") + progress: int = Field(description="An integer signifying the progress of the pull operation.") + is_completed: bool = Field(description="`True` if the pull operation is completed successfully. The `isCompleted` property is not queryable. To filter failed pull operations, query by `status!=Complete&&status!=NotSupported` instead.", alias="isCompleted") + is_errored: bool = Field(description="`True` if the pull operation entered an error state.", alias="isErrored") + __properties: ClassVar[List[str]] = ["id", "companyId", "connectionId", "dataType", "status", "statusDescription", "errorMessage", "requested", "completed", "progress", "isCompleted", "isErrored"] + + @field_validator('status') + def status_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['Initial', 'Queued', 'Fetching', 'MapQueued', 'Mapping', 'Complete', 'FetchError', 'MapError', 'InternalError', 'ProcessingQueued', 'Processing', 'ProcessingError', 'ValidationQueued', 'Validating', 'ValidationError', 'AuthError', 'Cancelled', 'NotSupported', 'RateLimitError', 'PermissionsError', 'PrerequisiteNotMet']): + raise ValueError("must be one of enum values ('Initial', 'Queued', 'Fetching', 'MapQueued', 'Mapping', 'Complete', 'FetchError', 'MapError', 'InternalError', 'ProcessingQueued', 'Processing', 'ProcessingError', 'ValidationQueued', 'Validating', 'ValidationError', 'AuthError', 'Cancelled', 'NotSupported', 'RateLimitError', 'PermissionsError', 'PrerequisiteNotMet')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PullOperation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PullOperation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "companyId": obj.get("companyId"), + "connectionId": obj.get("connectionId"), + "dataType": obj.get("dataType"), + "status": obj.get("status"), + "statusDescription": obj.get("statusDescription"), + "errorMessage": obj.get("errorMessage"), + "requested": obj.get("requested"), + "completed": obj.get("completed"), + "progress": obj.get("progress"), + "isCompleted": obj.get("isCompleted"), + "isErrored": obj.get("isErrored") + }) + return _obj - status: DatasetStatus - r"""The current status of the dataset.""" - - completed: Optional[str] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - - error_message: Annotated[ - OptionalNullable[str], pydantic.Field(alias="errorMessage") - ] = UNSET - r"""A message about a transient or persistent error returned by Codat or the source platform.""" - - status_description: Annotated[ - OptionalNullable[str], pydantic.Field(alias="statusDescription") - ] = UNSET - r"""Additional information about the dataset status.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["completed", "errorMessage", "statusDescription"]) - nullable_fields = set(["errorMessage", "statusDescription"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - PullOperation.model_rebuild() -except NameError: - pass +class PullOperationTypedDict(TypedDict): + """TypedDict variant of PullOperation, for dict-literal request/response inputs.""" + id: NotRequired[str] + company_id: NotRequired[str] + connection_id: NotRequired[str] + data_type: NotRequired[str] + status: NotRequired[DatasetStatus] + status_description: NotRequired[Optional[str]] + error_message: NotRequired[Optional[str]] + requested: NotRequired[str] + completed: NotRequired[Optional[str]] + progress: NotRequired[int] + is_completed: NotRequired[bool] + is_errored: NotRequired[bool] diff --git a/platform/src/codat_platform/models/shared/pulloperations.py b/platform/src/codat_platform/models/shared/pulloperations.py index 766448628..709601b19 100644 --- a/platform/src/codat_platform/models/shared/pulloperations.py +++ b/platform/src/codat_platform/models/shared/pulloperations.py @@ -1,58 +1,124 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .links import Links, LinksTypedDict -from .pulloperation import PullOperation, PullOperationTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.links import Links, LinksTypedDict +from codat_platform.models.shared.pulloperation import PullOperation, PullOperationTypedDict +from typing import Optional, Set +from typing_extensions import Self +class PullOperations(BaseModel): -class PullOperationsTypedDict(TypedDict): - links: LinksTypedDict - page_number: int - r"""Current page number.""" - page_size: int - r"""Number of items to return in results array.""" - total_results: int - r"""Total number of items.""" - results: NotRequired[List[PullOperationTypedDict]] + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + PullOperations + """ # noqa: E501 + page_number: int = Field(description="Current page number.", alias="pageNumber") + page_size: int = Field(description="Number of items to return in results array.", alias="pageSize") + total_results: int = Field(description="Total number of items.", alias="totalResults") + links: Links = Field(alias="_links") + results: Optional[List[PullOperation]] = None + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links", "results"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class PullOperations(BaseModel): - links: Annotated[Links, pydantic.Field(alias="_links")] - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PullOperations from a JSON string""" + return cls.from_dict(json.loads(json_str)) - results: Optional[List[PullOperation]] = None + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["results"]) - serialized = handler(self) - m = {} + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['_links'] = self.links.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + return _dict - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PullOperations from a dict""" + if obj is None: + return None - return m + if not isinstance(obj, dict): + return cls.model_validate(obj) + _obj = cls.model_validate({ + "pageNumber": obj.get("pageNumber"), + "pageSize": obj.get("pageSize"), + "totalResults": obj.get("totalResults"), + "_links": Links.from_dict(obj["_links"]) if obj.get("_links") is not None else None, + "results": [PullOperation.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj -try: - PullOperations.model_rebuild() -except NameError: - pass + + + + +class PullOperationsTypedDict(TypedDict): + """TypedDict variant of PullOperations, for dict-literal request/response inputs.""" + page_number: NotRequired[int] + page_size: NotRequired[int] + total_results: NotRequired[int] + links: NotRequired[LinksTypedDict] + results: NotRequired[Optional[List[PullOperationTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/pushchangetype.py b/platform/src/codat_platform/models/shared/pushchangetype.py index 76371e9e3..44b63958a 100644 --- a/platform/src/codat_platform/models/shared/pushchangetype.py +++ b/platform/src/codat_platform/models/shared/pushchangetype.py @@ -1,14 +1,40 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class PushChangeType(str, Enum): - r"""Type of change being applied to record in third party platform.""" + """ + Type of change being applied to record in third party platform. + """ + + """ + allowed enum values + """ + UNKNOWN = 'Unknown' + CREATED = 'Created' + MODIFIED = 'Modified' + DELETED = 'Deleted' + ATTACHMENT_UPLOADED = 'AttachmentUploaded' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PushChangeType from a JSON string""" + return cls(json.loads(json_str)) + - UNKNOWN = "Unknown" - CREATED = "Created" - MODIFIED = "Modified" - DELETED = "Deleted" - ATTACHMENT_UPLOADED = "AttachmentUploaded" diff --git a/platform/src/codat_platform/models/shared/pushfieldvalidation.py b/platform/src/codat_platform/models/shared/pushfieldvalidation.py index 842914aa7..e8eeb4389 100644 --- a/platform/src/codat_platform/models/shared/pushfieldvalidation.py +++ b/platform/src/codat_platform/models/shared/pushfieldvalidation.py @@ -1,58 +1,125 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class PushFieldValidationTypedDict(TypedDict): - details: str - r"""Details on the validation issue.""" - field: NotRequired[str] - r"""Field name that resulted in the validation issue.""" - ref: NotRequired[Nullable[str]] - r"""Unique reference identifier for the validation issue.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class PushFieldValidation(BaseModel): - details: str - r"""Details on the validation issue.""" - field: Optional[str] = None - r"""Field name that resulted in the validation issue.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - ref: OptionalNullable[str] = UNSET - r"""Unique reference identifier for the validation issue.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from typing import Optional, Set +from typing_extensions import Self + +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL +class PushFieldValidation(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["field", "ref"]) - nullable_fields = set(["ref"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m + _nullable = {'ref'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + PushFieldValidation + """ # noqa: E501 + field: Optional[str] = Field(default=None, description="Field name that resulted in the validation issue.", alias="field") + details: str = Field(description="Details on the validation issue.") + ref: OptionalNullable[str] = Field(default=UNSET, description="Unique reference identifier for the validation issue.") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["field", "details", "ref"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushFieldValidation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushFieldValidation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "field": obj.get("field"), + "details": obj.get("details"), + "ref": obj.get("ref") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + + + + +class PushFieldValidationTypedDict(TypedDict): + """TypedDict variant of PushFieldValidation, for dict-literal request/response inputs.""" + field: NotRequired[Optional[str]] + details: NotRequired[str] + ref: NotRequired[Optional[str]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/platform/src/codat_platform/models/shared/pushoperation.py b/platform/src/codat_platform/models/shared/pushoperation.py index 0d0f6d82a..fef6d886d 100644 --- a/platform/src/codat_platform/models/shared/pushoperation.py +++ b/platform/src/codat_platform/models/shared/pushoperation.py @@ -1,219 +1,164 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .datatype import DataType -from .pushoperationchange import PushOperationChange, PushOperationChangeTypedDict -from .pushoperationstatus import PushOperationStatus -from .validation import Validation, ValidationTypedDict -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class PushOperationTypedDict(TypedDict): - company_id: str - r"""Unique identifier for your SMB in Codat.""" - data_connection_key: str - r"""Unique identifier for a company's data connection.""" - push_operation_key: str - r"""A unique identifier generated by Codat to represent this single push operation. This identifier can be used to track the status of the push, and should be persisted.""" - requested_on_utc: str - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - status: PushOperationStatus - r"""The current status of the push operation.""" - status_code: int - r"""Push status code.""" - changes: NotRequired[Nullable[List[PushOperationChangeTypedDict]]] - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - completed_on_utc: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: +""" + Platform API - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - data_type: NotRequired[DataType] - r"""Available data types""" - error_message: NotRequired[Nullable[str]] - r"""A message about the error.""" - timeout_in_minutes: NotRequired[Nullable[int]] - r"""Number of minutes the push operation must complete within before it times out.""" - timeout_in_seconds: NotRequired[Nullable[int]] - r"""Number of seconds the push operation must complete within before it times out.""" - validation: NotRequired[ValidationTypedDict] - r"""A human-readable object describing validation decisions Codat has made when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here.""" + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from codat_platform.models.shared.datatype import DataType +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.pushoperationchange import PushOperationChange, PushOperationChangeTypedDict +from codat_platform.models.shared.pushoperationstatus import PushOperationStatus +from codat_platform.models.shared.validation import Validation, ValidationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL class PushOperation(BaseModel): - company_id: Annotated[str, pydantic.Field(alias="companyId")] - r"""Unique identifier for your SMB in Codat.""" - - data_connection_key: Annotated[str, pydantic.Field(alias="dataConnectionKey")] - r"""Unique identifier for a company's data connection.""" - - push_operation_key: Annotated[str, pydantic.Field(alias="pushOperationKey")] - r"""A unique identifier generated by Codat to represent this single push operation. This identifier can be used to track the status of the push, and should be persisted.""" - - requested_on_utc: Annotated[str, pydantic.Field(alias="requestedOnUtc")] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'changes', 'errorMessage', 'error_message', 'timeoutInMinutes', 'timeoutInSeconds', 'timeout_in_minutes', 'timeout_in_seconds'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - + PushOperation + """ # noqa: E501 + changes: OptionalNullable[List[PushOperationChange]] = Field(default=UNSET, description="Contains a single entry that communicates which record has changed and the manner in which it changed. ") + data_type: Optional[DataType] = Field(default=None, description="Available data types", alias="dataType") + company_id: str = Field(description="Unique identifier for your SMB in Codat.", alias="companyId") + push_operation_key: str = Field(description="A unique identifier generated by Codat to represent this single push operation. This identifier can be used to track the status of the push, and should be persisted.", alias="pushOperationKey") + data_connection_key: str = Field(description="Unique identifier for a company's data connection.", alias="dataConnectionKey") + requested_on_utc: str = Field(description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="requestedOnUtc") + completed_on_utc: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="completedOnUtc") + timeout_in_minutes: OptionalNullable[int] = Field(default=UNSET, description="Number of minutes the push operation must complete within before it times out.", alias="timeoutInMinutes") + timeout_in_seconds: OptionalNullable[int] = Field(default=UNSET, description="Number of seconds the push operation must complete within before it times out.", alias="timeoutInSeconds") status: PushOperationStatus - r"""The current status of the push operation.""" - - status_code: Annotated[int, pydantic.Field(alias="statusCode")] - r"""Push status code.""" - - changes: OptionalNullable[List[PushOperationChange]] = UNSET - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - - completed_on_utc: Annotated[ - Optional[str], pydantic.Field(alias="completedOnUtc") - ] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - - data_type: Annotated[Optional[DataType], pydantic.Field(alias="dataType")] = None - r"""Available data types""" + error_message: OptionalNullable[str] = Field(default=UNSET, description="A message about the error.", alias="errorMessage") + validation: Optional[Validation] = None + status_code: int = Field(description="Push status code.", alias="statusCode") + __properties: ClassVar[List[str]] = ["changes", "dataType", "companyId", "pushOperationKey", "dataConnectionKey", "requestedOnUtc", "completedOnUtc", "timeoutInMinutes", "timeoutInSeconds", "status", "errorMessage", "validation", "statusCode"] + + @field_validator('data_type') + def data_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions']): + raise ValueError("must be one of enum values ('accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushOperation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in changes (list) + _items = [] + if self.changes: + for _item_changes in self.changes: + if _item_changes: + _items.append(_item_changes.to_dict()) + _dict['changes'] = _items + # override the default output from pydantic by calling `to_dict()` of validation + if self.validation: + _dict['validation'] = self.validation.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushOperation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "changes": [PushOperationChange.from_dict(_item) for _item in obj["changes"]] if obj.get("changes") is not None else None, + "dataType": obj.get("dataType"), + "companyId": obj.get("companyId"), + "pushOperationKey": obj.get("pushOperationKey"), + "dataConnectionKey": obj.get("dataConnectionKey"), + "requestedOnUtc": obj.get("requestedOnUtc"), + "completedOnUtc": obj.get("completedOnUtc"), + "timeoutInMinutes": obj.get("timeoutInMinutes"), + "timeoutInSeconds": obj.get("timeoutInSeconds"), + "status": obj.get("status"), + "errorMessage": obj.get("errorMessage"), + "validation": Validation.from_dict(obj["validation"]) if obj.get("validation") is not None else None, + "statusCode": obj.get("statusCode") + }) + return _obj - error_message: Annotated[ - OptionalNullable[str], pydantic.Field(alias="errorMessage") - ] = UNSET - r"""A message about the error.""" - timeout_in_minutes: Annotated[ - OptionalNullable[int], pydantic.Field(alias="timeoutInMinutes") - ] = UNSET - r"""Number of minutes the push operation must complete within before it times out.""" - timeout_in_seconds: Annotated[ - OptionalNullable[int], - pydantic.Field( - deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible.", - alias="timeoutInSeconds", - ), - ] = UNSET - r"""Number of seconds the push operation must complete within before it times out.""" - validation: Optional[Validation] = None - r"""A human-readable object describing validation decisions Codat has made when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "changes", - "completedOnUtc", - "dataType", - "errorMessage", - "timeoutInMinutes", - "timeoutInSeconds", - "validation", - ] - ) - nullable_fields = set( - ["changes", "errorMessage", "timeoutInMinutes", "timeoutInSeconds"] - ) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - PushOperation.model_rebuild() -except NameError: - pass +class PushOperationTypedDict(TypedDict): + """TypedDict variant of PushOperation, for dict-literal request/response inputs.""" + changes: NotRequired[Optional[List[PushOperationChangeTypedDict]]] + data_type: NotRequired[Optional[DataType]] + company_id: NotRequired[str] + push_operation_key: NotRequired[str] + data_connection_key: NotRequired[str] + requested_on_utc: NotRequired[str] + completed_on_utc: NotRequired[Optional[str]] + timeout_in_minutes: NotRequired[Optional[int]] + timeout_in_seconds: NotRequired[Optional[int]] + status: PushOperationStatus + error_message: NotRequired[Optional[str]] + validation: NotRequired[Optional[ValidationTypedDict]] + status_code: NotRequired[int] diff --git a/platform/src/codat_platform/models/shared/pushoperationchange.py b/platform/src/codat_platform/models/shared/pushoperationchange.py index cb18ba3fd..3d40e6f35 100644 --- a/platform/src/codat_platform/models/shared/pushoperationchange.py +++ b/platform/src/codat_platform/models/shared/pushoperationchange.py @@ -1,69 +1,115 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .pushchangetype import PushChangeType -from .pushoperationref import PushOperationRef, PushOperationRefTypedDict -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class PushOperationChangeTypedDict(TypedDict): - attachment_id: NotRequired[Nullable[str]] - r"""Unique identifier for the attachment created otherwise null.""" - record_ref: NotRequired[PushOperationRefTypedDict] - type: NotRequired[PushChangeType] - r"""Type of change being applied to record in third party platform.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class PushOperationChange(BaseModel): - attachment_id: Annotated[ - OptionalNullable[str], pydantic.Field(alias="attachmentId") - ] = UNSET - r"""Unique identifier for the attachment created otherwise null.""" - record_ref: Annotated[ - Optional[PushOperationRef], pydantic.Field(alias="recordRef") - ] = None +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - type: Optional[PushChangeType] = None - r"""Type of change being applied to record in third party platform.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.pushchangetype import PushChangeType +from codat_platform.models.shared.pushoperationref import PushOperationRef, PushOperationRefTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL +class PushOperationChange(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["attachmentId", "recordRef", "type"]) - nullable_fields = set(["attachmentId"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - PushOperationChange.model_rebuild() -except NameError: - pass + _nullable = {'attachmentId', 'attachment_id'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + PushOperationChange + """ # noqa: E501 + type: Optional[PushChangeType] = None + record_ref: Optional[PushOperationRef] = Field(default=None, alias="recordRef") + attachment_id: OptionalNullable[str] = Field(default=UNSET, description="Unique identifier for the attachment created otherwise null.", alias="attachmentId") + __properties: ClassVar[List[str]] = ["type", "recordRef", "attachmentId"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushOperationChange from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of record_ref + if self.record_ref: + _dict['recordRef'] = self.record_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushOperationChange from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "recordRef": PushOperationRef.from_dict(obj["recordRef"]) if obj.get("recordRef") is not None else None, + "attachmentId": obj.get("attachmentId") + }) + return _obj + + + + + +class PushOperationChangeTypedDict(TypedDict): + """TypedDict variant of PushOperationChange, for dict-literal request/response inputs.""" + type: NotRequired[Optional[PushChangeType]] + record_ref: NotRequired[Optional[PushOperationRefTypedDict]] + attachment_id: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/shared/pushoperationref.py b/platform/src/codat_platform/models/shared/pushoperationref.py index d0ea1619d..ae0c5cc2f 100644 --- a/platform/src/codat_platform/models/shared/pushoperationref.py +++ b/platform/src/codat_platform/models/shared/pushoperationref.py @@ -1,46 +1,127 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .datatype import DataType -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class PushOperationRefTypedDict(TypedDict): - data_type: NotRequired[DataType] - r"""Available data types""" - id: NotRequired[str] - r"""Unique identifier for a push operation.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class PushOperationRef(BaseModel): - data_type: Annotated[Optional[DataType], pydantic.Field(alias="dataType")] = None - r"""Available data types""" - id: Optional[str] = None - r"""Unique identifier for a push operation.""" +from __future__ import annotations +from codat_platform.models.shared.datatype import DataType +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class PushOperationRef(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["dataType", "id"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + PushOperationRef + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier for a push operation.") + data_type: Optional[DataType] = Field(default=None, description="Available data types", alias="dataType") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["id", "dataType"] + + @field_validator('data_type') + def data_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions']): + raise ValueError("must be one of enum values ('accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushOperationRef from a JSON string""" + return cls.from_dict(json.loads(json_str)) - return m + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: -try: - PushOperationRef.model_rebuild() -except NameError: - pass + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushOperationRef from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "dataType": obj.get("dataType") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + + + + +class PushOperationRefTypedDict(TypedDict): + """TypedDict variant of PushOperationRef, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + data_type: NotRequired[Optional[DataType]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/platform/src/codat_platform/models/shared/pushoperations.py b/platform/src/codat_platform/models/shared/pushoperations.py index b952036ea..6c62d1240 100644 --- a/platform/src/codat_platform/models/shared/pushoperations.py +++ b/platform/src/codat_platform/models/shared/pushoperations.py @@ -1,58 +1,124 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .links import Links, LinksTypedDict -from .pushoperation import PushOperation, PushOperationTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.links import Links, LinksTypedDict +from codat_platform.models.shared.pushoperation import PushOperation, PushOperationTypedDict +from typing import Optional, Set +from typing_extensions import Self +class PushOperations(BaseModel): -class PushOperationsTypedDict(TypedDict): - links: LinksTypedDict - page_number: int - r"""Current page number.""" - page_size: int - r"""Number of items to return in results array.""" - total_results: int - r"""Total number of items.""" - results: NotRequired[List[PushOperationTypedDict]] + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + PushOperations + """ # noqa: E501 + page_number: int = Field(description="Current page number.", alias="pageNumber") + page_size: int = Field(description="Number of items to return in results array.", alias="pageSize") + total_results: int = Field(description="Total number of items.", alias="totalResults") + links: Links = Field(alias="_links") + results: Optional[List[PushOperation]] = None + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links", "results"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class PushOperations(BaseModel): - links: Annotated[Links, pydantic.Field(alias="_links")] - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushOperations from a JSON string""" + return cls.from_dict(json.loads(json_str)) - results: Optional[List[PushOperation]] = None + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["results"]) - serialized = handler(self) - m = {} + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['_links'] = self.links.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + return _dict - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushOperations from a dict""" + if obj is None: + return None - return m + if not isinstance(obj, dict): + return cls.model_validate(obj) + _obj = cls.model_validate({ + "pageNumber": obj.get("pageNumber"), + "pageSize": obj.get("pageSize"), + "totalResults": obj.get("totalResults"), + "_links": Links.from_dict(obj["_links"]) if obj.get("_links") is not None else None, + "results": [PushOperation.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj -try: - PushOperations.model_rebuild() -except NameError: - pass + + + + +class PushOperationsTypedDict(TypedDict): + """TypedDict variant of PushOperations, for dict-literal request/response inputs.""" + page_number: NotRequired[int] + page_size: NotRequired[int] + total_results: NotRequired[int] + links: NotRequired[LinksTypedDict] + results: NotRequired[Optional[List[PushOperationTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/pushoperationstatus.py b/platform/src/codat_platform/models/shared/pushoperationstatus.py index 09fa8b1f2..24d945be6 100644 --- a/platform/src/codat_platform/models/shared/pushoperationstatus.py +++ b/platform/src/codat_platform/models/shared/pushoperationstatus.py @@ -1,13 +1,39 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class PushOperationStatus(str, Enum): - r"""The current status of the push operation.""" + """ + The current status of the push operation. + """ + + """ + allowed enum values + """ + PENDING = 'Pending' + FAILED = 'Failed' + SUCCESS = 'Success' + TIMED_OUT = 'TimedOut' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PushOperationStatus from a JSON string""" + return cls(json.loads(json_str)) + - PENDING = "Pending" - FAILED = "Failed" - SUCCESS = "Success" - TIMED_OUT = "TimedOut" diff --git a/platform/src/codat_platform/models/shared/pushoption.py b/platform/src/codat_platform/models/shared/pushoption.py index 305ee6764..fafb0c5fc 100644 --- a/platform/src/codat_platform/models/shared/pushoption.py +++ b/platform/src/codat_platform/models/shared/pushoption.py @@ -1,83 +1,149 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .pushoptionchoice import PushOptionChoice, PushOptionChoiceTypedDict -from .pushoptionproperty import PushOptionProperty, PushOptionPropertyTypedDict -from .pushoptiontype import PushOptionType -from .pushvalidationinfo import PushValidationInfo, PushValidationInfoTypedDict -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Dict, List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class PushOptionTypedDict(TypedDict): - display_name: str - r"""The property's display name.""" - required: bool - r"""The property is required if `True`.""" - type: PushOptionType - r"""The option type.""" - description: NotRequired[str] - r"""A description of the property.""" - options: NotRequired[Nullable[List[PushOptionChoiceTypedDict]]] - properties: NotRequired[Nullable[Dict[str, PushOptionPropertyTypedDict]]] - validation: NotRequired[PushValidationInfoTypedDict] +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class PushOption(BaseModel): - display_name: Annotated[str, pydantic.Field(alias="displayName")] - r"""The property's display name.""" - - required: bool - r"""The property is required if `True`.""" - - type: PushOptionType - r"""The option type.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - description: Optional[str] = None - r"""A description of the property.""" + Do not edit the class manually. +""" # noqa: E501 - options: OptionalNullable[List[PushOptionChoice]] = UNSET - properties: OptionalNullable[Dict[str, PushOptionProperty]] = UNSET +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - validation: Optional[PushValidationInfo] = None +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.pushoptionchoice import PushOptionChoice, PushOptionChoiceTypedDict +from codat_platform.models.shared.pushoptionproperty import PushOptionProperty, PushOptionPropertyTypedDict +from codat_platform.models.shared.pushoptiontype import PushOptionType +from codat_platform.models.shared.pushvalidationinfo import PushValidationInfo, PushValidationInfoTypedDict +from typing import Optional, Set +from typing_extensions import Self + +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL +class PushOption(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["description", "options", "properties", "validation"]) - nullable_fields = set(["options", "properties"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member + _nullable = {'options', 'properties'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + PushOption + """ # noqa: E501 + type: PushOptionType + display_name: str = Field(description="The property's display name.", alias="displayName") + description: Optional[str] = Field(default=None, description="A description of the property.") + required: bool = Field(description="The property is required if `True`.") + properties: OptionalNullable[Dict[str, PushOptionProperty]] = UNSET + options: OptionalNullable[List[PushOptionChoice]] = UNSET + validation: Optional[PushValidationInfo] = None + __properties: ClassVar[List[str]] = ["type", "displayName", "description", "required", "properties", "options", "validation"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushOption from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each value in properties (dict) + _field_dict = {} + if self.properties: + for _key_properties in self.properties: + if self.properties[_key_properties]: + _field_dict[_key_properties] = self.properties[_key_properties].to_dict() + _dict['properties'] = _field_dict + # override the default output from pydantic by calling `to_dict()` of each item in options (list) + _items = [] + if self.options: + for _item_options in self.options: + if _item_options: + _items.append(_item_options.to_dict()) + _dict['options'] = _items + # override the default output from pydantic by calling `to_dict()` of validation + if self.validation: + _dict['validation'] = self.validation.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushOption from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "displayName": obj.get("displayName"), + "description": obj.get("description"), + "required": obj.get("required"), + "properties": dict( + (_k, PushOptionProperty.from_dict(_v)) + for _k, _v in obj["properties"].items() ) + if obj.get("properties") is not None + else None, + "options": [PushOptionChoice.from_dict(_item) for _item in obj["options"]] if obj.get("options") is not None else None, + "validation": PushValidationInfo.from_dict(obj["validation"]) if obj.get("validation") is not None else None + }) + return _obj + - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - return m -try: - PushOption.model_rebuild() -except NameError: - pass +class PushOptionTypedDict(TypedDict): + """TypedDict variant of PushOption, for dict-literal request/response inputs.""" + type: PushOptionType + display_name: NotRequired[str] + description: NotRequired[Optional[str]] + required: NotRequired[bool] + properties: NotRequired[Optional[Dict[str, PushOptionPropertyTypedDict]]] + options: NotRequired[Optional[List[PushOptionChoiceTypedDict]]] + validation: NotRequired[Optional[PushValidationInfoTypedDict]] diff --git a/platform/src/codat_platform/models/shared/pushoptionchoice.py b/platform/src/codat_platform/models/shared/pushoptionchoice.py index 50e963c62..ea5d10a67 100644 --- a/platform/src/codat_platform/models/shared/pushoptionchoice.py +++ b/platform/src/codat_platform/models/shared/pushoptionchoice.py @@ -1,63 +1,113 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .pushoptiontype import PushOptionType -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.pushoptiontype import PushOptionType +from typing import Optional, Set +from typing_extensions import Self +class PushOptionChoice(BaseModel): -class PushOptionChoiceTypedDict(TypedDict): - description: NotRequired[str] - r"""A description of the property.""" - display_name: NotRequired[str] - r"""The property's display name.""" - required: NotRequired[bool] - r"""The property is required if `True`.""" - type: NotRequired[PushOptionType] - r"""The option type.""" - value: NotRequired[str] - r"""Allowed value for field.""" + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + PushOptionChoice + """ # noqa: E501 + value: Optional[str] = Field(default=None, description="Allowed value for field.") + type: Optional[PushOptionType] = None + display_name: Optional[str] = Field(default=None, description="The property's display name.", alias="displayName") + description: Optional[str] = Field(default=None, description="A description of the property.") + required: Optional[bool] = Field(default=None, description="The property is required if `True`.") + __properties: ClassVar[List[str]] = ["value", "type", "displayName", "description", "required"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class PushOptionChoice(BaseModel): - description: Optional[str] = None - r"""A description of the property.""" - display_name: Annotated[Optional[str], pydantic.Field(alias="displayName")] = None - r"""The property's display name.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - required: Optional[bool] = None - r"""The property is required if `True`.""" + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - type: Optional[PushOptionType] = None - r"""The option type.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushOptionChoice from a JSON string""" + return cls.from_dict(json.loads(json_str)) - value: Optional[str] = None - r"""Allowed value for field.""" + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["description", "displayName", "required", "type", "value"] + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - serialized = handler(self) - m = {} + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushOptionChoice from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + _obj = cls.model_validate({ + "value": obj.get("value"), + "type": obj.get("type"), + "displayName": obj.get("displayName"), + "description": obj.get("description"), + "required": obj.get("required") + }) + return _obj - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - PushOptionChoice.model_rebuild() -except NameError: - pass + +class PushOptionChoiceTypedDict(TypedDict): + """TypedDict variant of PushOptionChoice, for dict-literal request/response inputs.""" + value: NotRequired[Optional[str]] + type: NotRequired[Optional[PushOptionType]] + display_name: NotRequired[Optional[str]] + description: NotRequired[Optional[str]] + required: NotRequired[Optional[bool]] diff --git a/platform/src/codat_platform/models/shared/pushoptionproperty.py b/platform/src/codat_platform/models/shared/pushoptionproperty.py index ee5e159db..db7497f4f 100644 --- a/platform/src/codat_platform/models/shared/pushoptionproperty.py +++ b/platform/src/codat_platform/models/shared/pushoptionproperty.py @@ -1,82 +1,150 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from __future__ import annotations -from .pushoptionchoice import PushOptionChoice, PushOptionChoiceTypedDict -from .pushoptiontype import PushOptionType -from .pushvalidationinfo import PushValidationInfo, PushValidationInfoTypedDict -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Dict, List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +# coding: utf-8 +""" + Platform API -class PushOptionPropertyTypedDict(TypedDict): - description: str - r"""A description of the property.""" - display_name: str - r"""The property's display name.""" - required: bool - r"""The property is required if `True`.""" - type: PushOptionType - r"""The option type.""" - options: NotRequired[Nullable[List[PushOptionChoiceTypedDict]]] - properties: NotRequired[Nullable[Dict[str, PushOptionPropertyTypedDict]]] - validation: NotRequired[PushValidationInfoTypedDict] + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) -class PushOptionProperty(BaseModel): - description: str - r"""A description of the property.""" + Do not edit the class manually. +""" # noqa: E501 - display_name: Annotated[str, pydantic.Field(alias="displayName")] - r"""The property's display name.""" - required: bool - r"""The property is required if `True`.""" - - type: PushOptionType - r"""The option type.""" - - options: OptionalNullable[List[PushOptionChoice]] = UNSET +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - properties: OptionalNullable[Dict[str, PushOptionProperty]] = UNSET +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.pushoptionchoice import PushOptionChoice, PushOptionChoiceTypedDict +from codat_platform.models.shared.pushoptiontype import PushOptionType +from codat_platform.models.shared.pushvalidationinfo import PushValidationInfo, PushValidationInfoTypedDict +from typing import Optional, Set +from typing_extensions import Self - validation: Optional[PushValidationInfo] = None +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL +class PushOptionProperty(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["options", "properties", "validation"]) - nullable_fields = set(["options", "properties"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member + _nullable = {'options', 'properties'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + PushOptionProperty + """ # noqa: E501 + type: PushOptionType + display_name: str = Field(description="The property's display name.", alias="displayName") + description: str = Field(description="A description of the property.") + required: bool = Field(description="The property is required if `True`.") + properties: OptionalNullable[Dict[str, PushOptionProperty]] = UNSET + options: OptionalNullable[List[PushOptionChoice]] = UNSET + validation: Optional[PushValidationInfo] = None + __properties: ClassVar[List[str]] = ["type", "displayName", "description", "required", "properties", "options", "validation"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushOptionProperty from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each value in properties (dict) + _field_dict = {} + if self.properties: + for _key_properties in self.properties: + if self.properties[_key_properties]: + _field_dict[_key_properties] = self.properties[_key_properties].to_dict() + _dict['properties'] = _field_dict + # override the default output from pydantic by calling `to_dict()` of each item in options (list) + _items = [] + if self.options: + for _item_options in self.options: + if _item_options: + _items.append(_item_options.to_dict()) + _dict['options'] = _items + # override the default output from pydantic by calling `to_dict()` of validation + if self.validation: + _dict['validation'] = self.validation.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushOptionProperty from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "displayName": obj.get("displayName"), + "description": obj.get("description"), + "required": obj.get("required"), + "properties": dict( + (_k, PushOptionProperty.from_dict(_v)) + for _k, _v in obj["properties"].items() ) + if obj.get("properties") is not None + else None, + "options": [PushOptionChoice.from_dict(_item) for _item in obj["options"]] if obj.get("options") is not None else None, + "validation": PushValidationInfo.from_dict(obj["validation"]) if obj.get("validation") is not None else None + }) + return _obj + +# TODO: Rewrite to not use raise_errors +PushOptionProperty.model_rebuild(raise_errors=False) - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - return m -try: - PushOptionProperty.model_rebuild() -except NameError: - pass +class PushOptionPropertyTypedDict(TypedDict): + """TypedDict variant of PushOptionProperty, for dict-literal request/response inputs.""" + type: PushOptionType + display_name: NotRequired[str] + description: NotRequired[str] + required: NotRequired[bool] + properties: NotRequired[Optional[Dict[str, PushOptionPropertyTypedDict]]] + options: NotRequired[Optional[List[PushOptionChoiceTypedDict]]] + validation: NotRequired[Optional[PushValidationInfoTypedDict]] diff --git a/platform/src/codat_platform/models/shared/pushoptiontype.py b/platform/src/codat_platform/models/shared/pushoptiontype.py index c9c246f2a..afc4c9f9c 100644 --- a/platform/src/codat_platform/models/shared/pushoptiontype.py +++ b/platform/src/codat_platform/models/shared/pushoptiontype.py @@ -1,17 +1,43 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class PushOptionType(str, Enum): - r"""The option type.""" - - ARRAY = "Array" - OBJECT = "Object" - STRING = "String" - NUMBER = "Number" - BOOLEAN = "Boolean" - DATE_TIME = "DateTime" - FILE = "File" - MULTI_PART = "MultiPart" + """ + The option type. + """ + + """ + allowed enum values + """ + ARRAY = 'Array' + OBJECT = 'Object' + STRING = 'String' + NUMBER = 'Number' + BOOLEAN = 'Boolean' + DATE_TIME = 'DateTime' + FILE = 'File' + MULTI_PART = 'MultiPart' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PushOptionType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/platform/src/codat_platform/models/shared/pushvalidationinfo.py b/platform/src/codat_platform/models/shared/pushvalidationinfo.py index bfa9ac7a0..fefa657b6 100644 --- a/platform/src/codat_platform/models/shared/pushvalidationinfo.py +++ b/platform/src/codat_platform/models/shared/pushvalidationinfo.py @@ -1,50 +1,136 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .pushfieldvalidation import PushFieldValidation, PushFieldValidationTypedDict -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from pydantic import model_serializer -from typing import List -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class PushValidationInfoTypedDict(TypedDict): - information: NotRequired[Nullable[List[PushFieldValidationTypedDict]]] - warnings: NotRequired[Nullable[List[PushFieldValidationTypedDict]]] + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class PushValidationInfo(BaseModel): - information: OptionalNullable[List[PushFieldValidation]] = UNSET - warnings: OptionalNullable[List[PushFieldValidation]] = UNSET +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.pushfieldvalidation import PushFieldValidation, PushFieldValidationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL +class PushValidationInfo(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["information", "warnings"]) - nullable_fields = set(["information", "warnings"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m + _nullable = {'information', 'warnings'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + PushValidationInfo + """ # noqa: E501 + warnings: OptionalNullable[List[PushFieldValidation]] = UNSET + information: OptionalNullable[List[PushFieldValidation]] = UNSET + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["warnings", "information"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushValidationInfo from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in warnings (list) + _items = [] + if self.warnings: + for _item_warnings in self.warnings: + if _item_warnings: + _items.append(_item_warnings.to_dict()) + _dict['warnings'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in information (list) + _items = [] + if self.information: + for _item_information in self.information: + if _item_information: + _items.append(_item_information.to_dict()) + _dict['information'] = _items + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushValidationInfo from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "warnings": [PushFieldValidation.from_dict(_item) for _item in obj["warnings"]] if obj.get("warnings") is not None else None, + "information": [PushFieldValidation.from_dict(_item) for _item in obj["information"]] if obj.get("information") is not None else None + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + + + + +class PushValidationInfoTypedDict(TypedDict): + """TypedDict variant of PushValidationInfo, for dict-literal request/response inputs.""" + warnings: NotRequired[Optional[List[PushFieldValidationTypedDict]]] + information: NotRequired[Optional[List[PushFieldValidationTypedDict]]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/platform/src/codat_platform/models/shared/readcompletedwebhook.py b/platform/src/codat_platform/models/shared/readcompletedwebhook.py index 6614dbec6..b61c917c6 100644 --- a/platform/src/codat_platform/models/shared/readcompletedwebhook.py +++ b/platform/src/codat_platform/models/shared/readcompletedwebhook.py @@ -1,97 +1,112 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .readcompletedwebhookpayload import ( - ReadCompletedWebhookPayload, - ReadCompletedWebhookPayloadTypedDict, -) -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ReadCompletedWebhookTypedDict(TypedDict): - event_type: NotRequired[str] - r"""The type of event.""" - generated_date: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.readcompletedwebhookpayload import ReadCompletedWebhookPayload, ReadCompletedWebhookPayloadTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` +class ReadCompletedWebhook(BaseModel): - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} """ - id: NotRequired[str] - r"""Unique identifier of the event.""" - payload: NotRequired[ReadCompletedWebhookPayloadTypedDict] + ReadCompletedWebhook + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the event.") + event_type: Optional[str] = Field(default=None, description="The type of event.", alias="eventType") + generated_date: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="generatedDate") + payload: Optional[ReadCompletedWebhookPayload] = None + __properties: ClassVar[List[str]] = ["id", "eventType", "generatedDate", "payload"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class ReadCompletedWebhook(BaseModel): - event_type: Annotated[Optional[str], pydantic.Field(alias="eventType")] = None - r"""The type of event.""" - generated_date: Annotated[Optional[str], pydantic.Field(alias="generatedDate")] = ( - None - ) - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ReadCompletedWebhook from a JSON string""" + return cls.from_dict(json.loads(json_str)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of payload + if self.payload: + _dict['payload'] = self.payload.to_dict() + return _dict - id: Optional[str] = None - r"""Unique identifier of the event.""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ReadCompletedWebhook from a dict""" + if obj is None: + return None - payload: Optional[ReadCompletedWebhookPayload] = None + if not isinstance(obj, dict): + return cls.model_validate(obj) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["eventType", "generatedDate", "id", "payload"]) - serialized = handler(self) - m = {} + _obj = cls.model_validate({ + "id": obj.get("id"), + "eventType": obj.get("eventType"), + "generatedDate": obj.get("generatedDate"), + "payload": ReadCompletedWebhookPayload.from_dict(obj["payload"]) if obj.get("payload") is not None else None + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - ReadCompletedWebhook.model_rebuild() -except NameError: - pass +class ReadCompletedWebhookTypedDict(TypedDict): + """TypedDict variant of ReadCompletedWebhook, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + event_type: NotRequired[Optional[str]] + generated_date: NotRequired[Optional[str]] + payload: NotRequired[Optional[ReadCompletedWebhookPayloadTypedDict]] diff --git a/platform/src/codat_platform/models/shared/readcompletedwebhookpayload.py b/platform/src/codat_platform/models/shared/readcompletedwebhookpayload.py index 900f23eaf..8a6ea4de6 100644 --- a/platform/src/codat_platform/models/shared/readcompletedwebhookpayload.py +++ b/platform/src/codat_platform/models/shared/readcompletedwebhookpayload.py @@ -1,92 +1,117 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .companyreference import CompanyReference, CompanyReferenceTypedDict -from .datatypereadsummary import DataTypeReadSummary, DataTypeReadSummaryTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ReadCompletedWebhookPayloadTypedDict(TypedDict): - data_types: NotRequired[List[DataTypeReadSummaryTypedDict]] - modified_from_date: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + Do not edit the class manually. +""" # noqa: E501 - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - reference_company: NotRequired[CompanyReferenceTypedDict] +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.companyreference import CompanyReference, CompanyReferenceTypedDict +from codat_platform.models.shared.datatypereadsummary import DataTypeReadSummary, DataTypeReadSummaryTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class ReadCompletedWebhookPayload(BaseModel): - data_types: Annotated[ - Optional[List[DataTypeReadSummary]], pydantic.Field(alias="dataTypes") - ] = None - - modified_from_date: Annotated[ - Optional[str], pydantic.Field(alias="modifiedFromDate") - ] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - - reference_company: Annotated[ - Optional[CompanyReference], pydantic.Field(alias="referenceCompany") - ] = None @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["dataTypes", "modifiedFromDate", "referenceCompany"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + ReadCompletedWebhookPayload + """ # noqa: E501 + reference_company: Optional[CompanyReference] = Field(default=None, alias="referenceCompany") + modified_from_date: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="modifiedFromDate") + data_types: Optional[List[DataTypeReadSummary]] = Field(default=None, alias="dataTypes") + __properties: ClassVar[List[str]] = ["referenceCompany", "modifiedFromDate", "dataTypes"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ReadCompletedWebhookPayload from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of reference_company + if self.reference_company: + _dict['referenceCompany'] = self.reference_company.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in data_types (list) + _items = [] + if self.data_types: + for _item_data_types in self.data_types: + if _item_data_types: + _items.append(_item_data_types.to_dict()) + _dict['dataTypes'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ReadCompletedWebhookPayload from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "referenceCompany": CompanyReference.from_dict(obj["referenceCompany"]) if obj.get("referenceCompany") is not None else None, + "modifiedFromDate": obj.get("modifiedFromDate"), + "dataTypes": [DataTypeReadSummary.from_dict(_item) for _item in obj["dataTypes"]] if obj.get("dataTypes") is not None else None + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - ReadCompletedWebhookPayload.model_rebuild() -except NameError: - pass +class ReadCompletedWebhookPayloadTypedDict(TypedDict): + """TypedDict variant of ReadCompletedWebhookPayload, for dict-literal request/response inputs.""" + reference_company: NotRequired[Optional[CompanyReferenceTypedDict]] + modified_from_date: NotRequired[Optional[str]] + data_types: NotRequired[Optional[List[DataTypeReadSummaryTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/schema_datatype.py b/platform/src/codat_platform/models/shared/schema_datatype.py index aa72f531c..3116cda65 100644 --- a/platform/src/codat_platform/models/shared/schema_datatype.py +++ b/platform/src/codat_platform/models/shared/schema_datatype.py @@ -1,52 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - from __future__ import annotations -from enum import Enum +from enum import Enum -class SchemaDataType(str, Enum): - r"""Available data types""" - ACCOUNT_TRANSACTIONS = "accountTransactions" - BALANCE_SHEET = "balanceSheet" - BANK_ACCOUNTS = "bankAccounts" - BANK_TRANSACTIONS = "bankTransactions" - BILL_CREDIT_NOTES = "billCreditNotes" - BILL_PAYMENTS = "billPayments" - BILLS = "bills" - CASH_FLOW_STATEMENT = "cashFlowStatement" - CHART_OF_ACCOUNTS = "chartOfAccounts" - COMPANY = "company" - CREDIT_NOTES = "creditNotes" - CUSTOMERS = "customers" - DIRECT_COSTS = "directCosts" - DIRECT_INCOMES = "directIncomes" - INVOICES = "invoices" - ITEM_RECEIPTS = "itemReceipts" - ITEMS = "items" - JOURNAL_ENTRIES = "journalEntries" - JOURNALS = "journals" - PAYMENT_METHODS = "paymentMethods" - PAYMENTS = "payments" - PROFIT_AND_LOSS = "profitAndLoss" - PURCHASE_ORDERS = "purchaseOrders" - SALES_ORDERS = "salesOrders" - SUPPLIERS = "suppliers" - TAX_RATES = "taxRates" - TRACKING_CATEGORIES = "trackingCategories" - TRANSFERS = "transfers" - BANKING_ACCOUNT_BALANCES = "banking-accountBalances" - BANKING_ACCOUNTS = "banking-accounts" - BANKING_TRANSACTION_CATEGORIES = "banking-transactionCategories" - BANKING_TRANSACTIONS = "banking-transactions" - COMMERCE_COMPANY_INFO = "commerce-companyInfo" - COMMERCE_CUSTOMERS = "commerce-customers" - COMMERCE_DISPUTES = "commerce-disputes" - COMMERCE_LOCATIONS = "commerce-locations" - COMMERCE_ORDERS = "commerce-orders" - COMMERCE_PAYMENT_METHODS = "commerce-paymentMethods" - COMMERCE_PAYMENTS = "commerce-payments" - COMMERCE_PRODUCT_CATEGORIES = "commerce-productCategories" - COMMERCE_PRODUCTS = "commerce-products" - COMMERCE_TAX_COMPONENTS = "commerce-taxComponents" - COMMERCE_TRANSACTIONS = "commerce-transactions" +from codat_platform.models._compat.schema_datatype import SchemaDataType diff --git a/platform/src/codat_platform/models/shared/security.py b/platform/src/codat_platform/models/shared/security.py index 8af319409..437733569 100644 --- a/platform/src/codat_platform/models/shared/security.py +++ b/platform/src/codat_platform/models/shared/security.py @@ -1,9 +1,12 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Security model for codat_platform. + +Generated by pipeline/postprocess_generated.py — do not edit by hand. +""" from __future__ import annotations -from codat_platform.types import BaseModel -from codat_platform.utils import FieldMetadata, SecurityMetadata -from typing_extensions import Annotated, TypedDict + +from pydantic import BaseModel +from typing_extensions import TypedDict class SecurityTypedDict(TypedDict): @@ -11,14 +14,5 @@ class SecurityTypedDict(TypedDict): class Security(BaseModel): - auth_header: Annotated[ - str, - FieldMetadata( - security=SecurityMetadata( - scheme=True, - scheme_type="apiKey", - sub_type="header", - field_name="Authorization", - ) - ), - ] + auth_header: str + r"""The word "Basic" followed by a space and your API key. [API keys](https://docs.codat.io/platform-api#/schemas/ApiKeyDetails) are tokens used to control access to the API. You can get an API key via [the Codat Portal](https://app.codat.io/developers/api-keys), via [the API](https://docs.codat.io/platform-api#/operations/list-api-keys), or [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat.""" diff --git a/platform/src/codat_platform/models/shared/sourcetype.py b/platform/src/codat_platform/models/shared/sourcetype.py index 91e562513..55ce142df 100644 --- a/platform/src/codat_platform/models/shared/sourcetype.py +++ b/platform/src/codat_platform/models/shared/sourcetype.py @@ -1,16 +1,43 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class SourceType(str, Enum): - r"""The type of platform of the connection.""" - - ACCOUNTING = "Accounting" - BANKING = "Banking" - BANK_FEED = "BankFeed" - COMMERCE = "Commerce" - EXPENSE = "Expense" - OTHER = "Other" - UNKNOWN = "Unknown" + """ + The type of platform of the connection. + """ + + """ + allowed enum values + """ + ACCOUNTING = 'Accounting' + BANKING = 'Banking' + BANK_FEED = 'BankFeed' + COMMERCE = 'Commerce' + EXPENSE = 'Expense' + OTHER = 'Other' + UNKNOWN = 'Unknown' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of SourceType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/platform/src/codat_platform/models/shared/status.py b/platform/src/codat_platform/models/shared/status.py index bab5b3828..d473db8a9 100644 --- a/platform/src/codat_platform/models/shared/status.py +++ b/platform/src/codat_platform/models/shared/status.py @@ -1,30 +1,56 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class Status(str, Enum): - r"""The current status of the dataset.""" - - INITIAL = "Initial" - QUEUED = "Queued" - FETCHING = "Fetching" - MAP_QUEUED = "MapQueued" - MAPPING = "Mapping" - COMPLETE = "Complete" - FETCH_ERROR = "FetchError" - MAP_ERROR = "MapError" - INTERNAL_ERROR = "InternalError" - PROCESSING_QUEUED = "ProcessingQueued" - PROCESSING = "Processing" - PROCESSING_ERROR = "ProcessingError" - VALIDATION_QUEUED = "ValidationQueued" - VALIDATING = "Validating" - VALIDATION_ERROR = "ValidationError" - AUTH_ERROR = "AuthError" - CANCELLED = "Cancelled" - NOT_SUPPORTED = "NotSupported" - RATE_LIMIT_ERROR = "RateLimitError" - PERMISSIONS_ERROR = "PermissionsError" - PREREQUISITE_NOT_MET = "PrerequisiteNotMet" + """ + The current status of the dataset. + """ + + """ + allowed enum values + """ + INITIAL = 'Initial' + QUEUED = 'Queued' + FETCHING = 'Fetching' + MAP_QUEUED = 'MapQueued' + MAPPING = 'Mapping' + COMPLETE = 'Complete' + FETCH_ERROR = 'FetchError' + MAP_ERROR = 'MapError' + INTERNAL_ERROR = 'InternalError' + PROCESSING_QUEUED = 'ProcessingQueued' + PROCESSING = 'Processing' + PROCESSING_ERROR = 'ProcessingError' + VALIDATION_QUEUED = 'ValidationQueued' + VALIDATING = 'Validating' + VALIDATION_ERROR = 'ValidationError' + AUTH_ERROR = 'AuthError' + CANCELLED = 'Cancelled' + NOT_SUPPORTED = 'NotSupported' + RATE_LIMIT_ERROR = 'RateLimitError' + PERMISSIONS_ERROR = 'PermissionsError' + PREREQUISITE_NOT_MET = 'PrerequisiteNotMet' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Status from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/platform/src/codat_platform/models/shared/supplementaldataconfiguration.py b/platform/src/codat_platform/models/shared/supplementaldataconfiguration.py index 107ed24a8..1e67a4307 100644 --- a/platform/src/codat_platform/models/shared/supplementaldataconfiguration.py +++ b/platform/src/codat_platform/models/shared/supplementaldataconfiguration.py @@ -1,91 +1,112 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Dict, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +# coding: utf-8 +""" + Platform API -class SupplementalDataSourceConfigurationTypedDict(TypedDict): - r"""The client's defined name for the object.""" + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | - data_source: NotRequired[str] - r"""The underlying endpoint of the source system which the configuration is targeting.""" - pull_data: NotRequired[Dict[str, str]] - r"""The additional properties that are required when pulling records.""" - push_data: NotRequired[Dict[str, str]] - r"""The additional properties that are required to create and/or update records.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class SupplementalDataSourceConfiguration(BaseModel): - r"""The client's defined name for the object.""" - data_source: Annotated[Optional[str], pydantic.Field(alias="dataSource")] = None - r"""The underlying endpoint of the source system which the configuration is targeting.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - pull_data: Annotated[Optional[Dict[str, str]], pydantic.Field(alias="pullData")] = ( - None - ) - r"""The additional properties that are required when pulling records.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.supplemental_data_source_configuration import SupplementalDataSourceConfiguration, SupplementalDataSourceConfigurationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - push_data: Annotated[Optional[Dict[str, str]], pydantic.Field(alias="pushData")] = ( - None - ) - r"""The additional properties that are required to create and/or update records.""" +class SupplementalDataConfiguration(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["dataSource", "pullData", "pushData"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + + """ # noqa: E501 + supplemental_data_config: Optional[Dict[str, SupplementalDataSourceConfiguration]] = Field(default=None, alias="supplementalDataConfig") + __properties: ClassVar[List[str]] = ["supplementalDataConfig"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - return m + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SupplementalDataConfiguration from a JSON string""" + return cls.from_dict(json.loads(json_str)) -class SupplementalDataConfigurationTypedDict(TypedDict): - supplemental_data_config: NotRequired[ - Dict[str, SupplementalDataSourceConfigurationTypedDict] - ] + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: -class SupplementalDataConfiguration(BaseModel): - supplemental_data_config: Annotated[ - Optional[Dict[str, SupplementalDataSourceConfiguration]], - pydantic.Field(alias="supplementalDataConfig"), - ] = None + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["supplementalDataConfig"]) - serialized = handler(self) - m = {} + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each value in supplemental_data_config (dict) + _field_dict = {} + if self.supplemental_data_config: + for _key_supplemental_data_config in self.supplemental_data_config: + if self.supplemental_data_config[_key_supplemental_data_config]: + _field_dict[_key_supplemental_data_config] = self.supplemental_data_config[_key_supplemental_data_config].to_dict() + _dict['supplementalDataConfig'] = _field_dict + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SupplementalDataConfiguration from a dict""" + if obj is None: + return None - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + if not isinstance(obj, dict): + return cls.model_validate(obj) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + _obj = cls.model_validate({ + "supplementalDataConfig": dict( + (_k, SupplementalDataSourceConfiguration.from_dict(_v)) + for _k, _v in obj["supplementalDataConfig"].items() + ) + if obj.get("supplementalDataConfig") is not None + else None + }) + return _obj - return m -try: - SupplementalDataSourceConfiguration.model_rebuild() -except NameError: - pass -try: - SupplementalDataConfiguration.model_rebuild() -except NameError: - pass + + +class SupplementalDataConfigurationTypedDict(TypedDict): + """TypedDict variant of SupplementalDataConfiguration, for dict-literal request/response inputs.""" + supplemental_data_config: NotRequired[Optional[Dict[str, SupplementalDataSourceConfigurationTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/supportedfeature.py b/platform/src/codat_platform/models/shared/supportedfeature.py index 6610bab76..075f4f1c5 100644 --- a/platform/src/codat_platform/models/shared/supportedfeature.py +++ b/platform/src/codat_platform/models/shared/supportedfeature.py @@ -1,29 +1,104 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .featurestate import FeatureState -from .featuretype import FeatureType -from codat_platform.types import BaseModel -import pydantic -from typing_extensions import Annotated, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class SupportedFeatureTypedDict(TypedDict): - feature_state: FeatureState - r"""The current release state of the feature.""" - feature_type: FeatureType - r"""The type of feature.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List +from codat_platform.models.shared.featurestate import FeatureState +from codat_platform.models.shared.featuretype import FeatureType +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class SupportedFeature(BaseModel): - feature_state: Annotated[FeatureState, pydantic.Field(alias="featureState")] - r"""The current release state of the feature.""" - feature_type: Annotated[FeatureType, pydantic.Field(alias="featureType")] - r"""The type of feature.""" + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + SupportedFeature + """ # noqa: E501 + feature_type: FeatureType = Field(alias="featureType") + feature_state: FeatureState = Field(alias="featureState") + __properties: ClassVar[List[str]] = ["featureType", "featureState"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SupportedFeature from a JSON string""" + return cls.from_dict(json.loads(json_str)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. -try: - SupportedFeature.model_rebuild() -except NameError: - pass + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SupportedFeature from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "featureType": obj.get("featureType"), + "featureState": obj.get("featureState") + }) + return _obj + + + + + +class SupportedFeatureTypedDict(TypedDict): + """TypedDict variant of SupportedFeature, for dict-literal request/response inputs.""" + feature_type: NotRequired[FeatureType] + feature_state: NotRequired[FeatureState] diff --git a/platform/src/codat_platform/models/shared/syncsetting.py b/platform/src/codat_platform/models/shared/syncsetting.py index d133ee191..8c31b69f4 100644 --- a/platform/src/codat_platform/models/shared/syncsetting.py +++ b/platform/src/codat_platform/models/shared/syncsetting.py @@ -1,124 +1,128 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .datatype import DataType -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class SyncSettingTypedDict(TypedDict): - r"""Describes how often, and how much history, should be fetched for the given data type when a pull operation is queued.""" - - data_type: DataType - r"""Available data types""" - fetch_on_first_link: bool - r"""Whether this data type should be queued after a company has authorized a connection.""" - sync_order: int - r"""The sync in which data types are queued for a sync.""" - sync_schedule: int - r"""Number of hours after which this data type should be refreshed.""" - is_locked: NotRequired[bool] - r"""`True` if the [sync setting](https://docs.codat.io/knowledge-base/advanced-sync-settings) is locked.""" - months_to_sync: NotRequired[int] - r"""Months of data to fetch, for report data types (`balanceSheet` & `profitAndLoss`) only.""" - sync_from_utc: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - sync_from_window: NotRequired[int] - r"""Number of months of data to be fetched. Set this *or* `syncFromUTC`.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class SyncSetting(BaseModel): - r"""Describes how often, and how much history, should be fetched for the given data type when a pull operation is queued.""" - data_type: Annotated[DataType, pydantic.Field(alias="dataType")] - r"""Available data types""" +from __future__ import annotations +from codat_platform.models.shared.datatype import DataType +import pprint +import re # noqa: F401 +import json - fetch_on_first_link: Annotated[bool, pydantic.Field(alias="fetchOnFirstLink")] - r"""Whether this data type should be queued after a company has authorized a connection.""" +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - sync_order: Annotated[int, pydantic.Field(alias="syncOrder")] - r"""The sync in which data types are queued for a sync.""" +class SyncSetting(BaseModel): - sync_schedule: Annotated[int, pydantic.Field(alias="syncSchedule")] - r"""Number of hours after which this data type should be refreshed.""" + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + Describes how often, and how much history, should be fetched for the given data type when a pull operation is queued. + """ # noqa: E501 + data_type: DataType = Field(description="Available data types", alias="dataType") + fetch_on_first_link: bool = Field(description="Whether this data type should be queued after a company has authorized a connection.", alias="fetchOnFirstLink") + sync_schedule: int = Field(description="Number of hours after which this data type should be refreshed.", alias="syncSchedule") + sync_order: int = Field(description="The sync in which data types are queued for a sync.", alias="syncOrder") + sync_from_utc: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="syncFromUtc") + sync_from_window: Optional[int] = Field(default=None, description="Number of months of data to be fetched. Set this *or* `syncFromUTC`.", alias="syncFromWindow") + months_to_sync: Optional[int] = Field(default=None, description="Months of data to fetch, for report data types (`balanceSheet` & `profitAndLoss`) only.", alias="monthsToSync") + is_locked: Optional[bool] = Field(default=None, description="`True` if the [sync setting](https://docs.codat.io/knowledge-base/advanced-sync-settings) is locked.", alias="isLocked") + __properties: ClassVar[List[str]] = ["dataType", "fetchOnFirstLink", "syncSchedule", "syncOrder", "syncFromUtc", "syncFromWindow", "monthsToSync", "isLocked"] + + @field_validator('data_type') + def data_type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions']): + raise ValueError("must be one of enum values ('accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - is_locked: Annotated[Optional[bool], pydantic.Field(alias="isLocked")] = None - r"""`True` if the [sync setting](https://docs.codat.io/knowledge-base/advanced-sync-settings) is locked.""" - months_to_sync: Annotated[Optional[int], pydantic.Field(alias="monthsToSync")] = ( - None - ) - r"""Months of data to fetch, for report data types (`balanceSheet` & `profitAndLoss`) only.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - sync_from_utc: Annotated[Optional[str], pydantic.Field(alias="syncFromUtc")] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SyncSetting from a JSON string""" + return cls.from_dict(json.loads(json_str)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SyncSetting from a dict""" + if obj is None: + return None - sync_from_window: Annotated[ - Optional[int], pydantic.Field(alias="syncFromWindow") - ] = None - r"""Number of months of data to be fetched. Set this *or* `syncFromUTC`.""" + if not isinstance(obj, dict): + return cls.model_validate(obj) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["isLocked", "monthsToSync", "syncFromUtc", "syncFromWindow"] - ) - serialized = handler(self) - m = {} + _obj = cls.model_validate({ + "dataType": obj.get("dataType"), + "fetchOnFirstLink": obj.get("fetchOnFirstLink"), + "syncSchedule": obj.get("syncSchedule"), + "syncOrder": obj.get("syncOrder"), + "syncFromUtc": obj.get("syncFromUtc"), + "syncFromWindow": obj.get("syncFromWindow"), + "monthsToSync": obj.get("monthsToSync"), + "isLocked": obj.get("isLocked") + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - SyncSetting.model_rebuild() -except NameError: - pass +class SyncSettingTypedDict(TypedDict): + """TypedDict variant of SyncSetting, for dict-literal request/response inputs.""" + data_type: NotRequired[DataType] + fetch_on_first_link: NotRequired[bool] + sync_schedule: NotRequired[int] + sync_order: NotRequired[int] + sync_from_utc: NotRequired[Optional[str]] + sync_from_window: NotRequired[Optional[int]] + months_to_sync: NotRequired[Optional[int]] + is_locked: NotRequired[Optional[bool]] diff --git a/platform/src/codat_platform/models/shared/syncsettings.py b/platform/src/codat_platform/models/shared/syncsettings.py index 52315fb69..6b8103b4f 100644 --- a/platform/src/codat_platform/models/shared/syncsettings.py +++ b/platform/src/codat_platform/models/shared/syncsettings.py @@ -1,51 +1,113 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .syncsetting import SyncSetting, SyncSettingTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class SyncSettingsTypedDict(TypedDict): - client_id: NotRequired[str] - r"""Unique identifier for your client in Codat.""" - overrides_defaults: NotRequired[bool] - r"""Set to `True` if you want to override the default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings).""" - settings: NotRequired[List[SyncSettingTypedDict]] + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class SyncSettings(BaseModel): - client_id: Annotated[Optional[str], pydantic.Field(alias="clientId")] = None - r"""Unique identifier for your client in Codat.""" - overrides_defaults: Annotated[ - Optional[bool], pydantic.Field(alias="overridesDefaults") - ] = None - r"""Set to `True` if you want to override the default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings).""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - settings: Optional[List[SyncSetting]] = None +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.syncsetting import SyncSetting, SyncSettingTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class SyncSettings(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["clientId", "overridesDefaults", "settings"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + SyncSettings + """ # noqa: E501 + client_id: Optional[str] = Field(default=None, description="Unique identifier for your client in Codat.", alias="clientId") + settings: Optional[List[SyncSetting]] = None + overrides_defaults: Optional[bool] = Field(default=None, description="Set to `True` if you want to override the default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings).", alias="overridesDefaults") + __properties: ClassVar[List[str]] = ["clientId", "settings", "overridesDefaults"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SyncSettings from a JSON string""" + return cls.from_dict(json.loads(json_str)) - return m + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: -try: - SyncSettings.model_rebuild() -except NameError: - pass + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in settings (list) + _items = [] + if self.settings: + for _item_settings in self.settings: + if _item_settings: + _items.append(_item_settings.to_dict()) + _dict['settings'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SyncSettings from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "clientId": obj.get("clientId"), + "settings": [SyncSetting.from_dict(_item) for _item in obj["settings"]] if obj.get("settings") is not None else None, + "overridesDefaults": obj.get("overridesDefaults") + }) + return _obj + + + + + +class SyncSettingsTypedDict(TypedDict): + """TypedDict variant of SyncSettings, for dict-literal request/response inputs.""" + client_id: NotRequired[Optional[str]] + settings: NotRequired[Optional[List[SyncSettingTypedDict]]] + overrides_defaults: NotRequired[Optional[bool]] diff --git a/platform/src/codat_platform/models/shared/updateconnectionstatus.py b/platform/src/codat_platform/models/shared/updateconnectionstatus.py index 89510833d..d2194136c 100644 --- a/platform/src/codat_platform/models/shared/updateconnectionstatus.py +++ b/platform/src/codat_platform/models/shared/updateconnectionstatus.py @@ -1,34 +1,114 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .dataconnectionstatus import DataConnectionStatus -from codat_platform.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class UpdateConnectionStatusTypedDict(TypedDict): - status: NotRequired[DataConnectionStatus] - r"""The current authorization status of the data connection.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.dataconnectionstatus import DataConnectionStatus +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class UpdateConnectionStatus(BaseModel): - status: Optional[DataConnectionStatus] = None - r"""The current authorization status of the data connection.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["status"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + UpdateConnectionStatus + """ # noqa: E501 + status: Optional[DataConnectionStatus] = Field(default=None, description="The current authorization status of the data connection.") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["status"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of UpdateConnectionStatus from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) - return m + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UpdateConnectionStatus from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "status": obj.get("status") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + + + + +class UpdateConnectionStatusTypedDict(TypedDict): + """TypedDict variant of UpdateConnectionStatus, for dict-literal request/response inputs.""" + status: NotRequired[Optional[DataConnectionStatus]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/platform/src/codat_platform/models/shared/validation.py b/platform/src/codat_platform/models/shared/validation.py index e5da60ba5..5a319e3a3 100644 --- a/platform/src/codat_platform/models/shared/validation.py +++ b/platform/src/codat_platform/models/shared/validation.py @@ -1,54 +1,122 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .validationitem import ValidationItem, ValidationItemTypedDict -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from pydantic import model_serializer -from typing import List -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ValidationTypedDict(TypedDict): - r"""A human-readable object describing validation decisions Codat has made when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - errors: NotRequired[Nullable[List[ValidationItemTypedDict]]] - warnings: NotRequired[Nullable[List[ValidationItemTypedDict]]] + Do not edit the class manually. +""" # noqa: E501 -class Validation(BaseModel): - r"""A human-readable object describing validation decisions Codat has made when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - errors: OptionalNullable[List[ValidationItem]] = UNSET +from pydantic import BaseModel, ConfigDict, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.shared.validationitem import ValidationItem, ValidationItemTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - warnings: OptionalNullable[List[ValidationItem]] = UNSET +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL +class Validation(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["errors", "warnings"]) - nullable_fields = set(["errors", "warnings"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m + _nullable = {'errors', 'warnings'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + A human-readable object describing validation decisions Codat has made when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here. + """ # noqa: E501 + errors: OptionalNullable[List[ValidationItem]] = UNSET + warnings: OptionalNullable[List[ValidationItem]] = UNSET + __properties: ClassVar[List[str]] = ["errors", "warnings"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Validation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in errors (list) + _items = [] + if self.errors: + for _item_errors in self.errors: + if _item_errors: + _items.append(_item_errors.to_dict()) + _dict['errors'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in warnings (list) + _items = [] + if self.warnings: + for _item_warnings in self.warnings: + if _item_warnings: + _items.append(_item_warnings.to_dict()) + _dict['warnings'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Validation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "errors": [ValidationItem.from_dict(_item) for _item in obj["errors"]] if obj.get("errors") is not None else None, + "warnings": [ValidationItem.from_dict(_item) for _item in obj["warnings"]] if obj.get("warnings") is not None else None + }) + return _obj + + + + + +class ValidationTypedDict(TypedDict): + """TypedDict variant of Validation, for dict-literal request/response inputs.""" + errors: NotRequired[Optional[List[ValidationItemTypedDict]]] + warnings: NotRequired[Optional[List[ValidationItemTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/validationitem.py b/platform/src/codat_platform/models/shared/validationitem.py index 5fa1048ce..e81c3c342 100644 --- a/platform/src/codat_platform/models/shared/validationitem.py +++ b/platform/src/codat_platform/models/shared/validationitem.py @@ -1,66 +1,124 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ValidationItemTypedDict(TypedDict): - item_id: NotRequired[Nullable[str]] - r"""Unique identifier for a validation item.""" - message: NotRequired[Nullable[str]] - r"""A message outlining validation item's issue.""" - validator_name: NotRequired[Nullable[str]] - r"""Name of validator.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class ValidationItem(BaseModel): - item_id: Annotated[OptionalNullable[str], pydantic.Field(alias="itemId")] = UNSET - r"""Unique identifier for a validation item.""" - message: OptionalNullable[str] = UNSET - r"""A message outlining validation item's issue.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - validator_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="validatorName") - ] = UNSET - r"""Name of validator.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL +class ValidationItem(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["itemId", "message", "validatorName"]) - nullable_fields = set(["itemId", "message", "validatorName"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - ValidationItem.model_rebuild() -except NameError: - pass + _nullable = {'itemId', 'item_id', 'message', 'validatorName', 'validator_name'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + ValidationItem + """ # noqa: E501 + item_id: OptionalNullable[str] = Field(default=UNSET, description="Unique identifier for a validation item.", alias="itemId") + message: OptionalNullable[str] = Field(default=UNSET, description="A message outlining validation item's issue.") + validator_name: OptionalNullable[str] = Field(default=UNSET, description="Name of validator.", alias="validatorName") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["itemId", "message", "validatorName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ValidationItem from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ValidationItem from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "itemId": obj.get("itemId"), + "message": obj.get("message"), + "validatorName": obj.get("validatorName") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + + + + +class ValidationItemTypedDict(TypedDict): + """TypedDict variant of ValidationItem, for dict-literal request/response inputs.""" + item_id: NotRequired[Optional[str]] + message: NotRequired[Optional[str]] + validator_name: NotRequired[Optional[str]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/platform/src/codat_platform/models/shared/validationitem1.py b/platform/src/codat_platform/models/shared/validationitem1.py deleted file mode 100644 index cb3db24f7..000000000 --- a/platform/src/codat_platform/models/shared/validationitem1.py +++ /dev/null @@ -1,57 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from __future__ import annotations -from codat_platform.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ValidationItem1TypedDict(TypedDict): - item_id: NotRequired[str] - r"""The unique identifier of the item that was validated.""" - message: NotRequired[str] - r"""The message that describes the validation warning or error.""" - rule_id: NotRequired[str] - r"""The unique identifier of the rule that wasn't met.""" - validator_name: NotRequired[str] - r"""The name of the validator that was used to validate the item.""" - - -class ValidationItem1(BaseModel): - item_id: Annotated[Optional[str], pydantic.Field(alias="itemId")] = None - r"""The unique identifier of the item that was validated.""" - - message: Optional[str] = None - r"""The message that describes the validation warning or error.""" - - rule_id: Annotated[Optional[str], pydantic.Field(alias="ruleId")] = None - r"""The unique identifier of the rule that wasn't met.""" - - validator_name: Annotated[Optional[str], pydantic.Field(alias="validatorName")] = ( - None - ) - r"""The name of the validator that was used to validate the item.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["itemId", "message", "ruleId", "validatorName"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m - - -try: - ValidationItem1.model_rebuild() -except NameError: - pass diff --git a/platform/src/codat_platform/models/shared/validationresult.py b/platform/src/codat_platform/models/shared/validationresult.py index 4b95ffab5..46cd9a102 100644 --- a/platform/src/codat_platform/models/shared/validationresult.py +++ b/platform/src/codat_platform/models/shared/validationresult.py @@ -1,35 +1,118 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .validationitem1 import ValidationItem1, ValidationItem1TypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class ValidationResultTypedDict(TypedDict): - errors: NotRequired[List[ValidationItem1TypedDict]] - warnings: NotRequired[List[ValidationItem1TypedDict]] + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class ValidationResult(BaseModel): - errors: Optional[List[ValidationItem1]] = None - warnings: Optional[List[ValidationItem1]] = None +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_platform.models.validation_item1 import ValidationItem1, ValidationItem1TypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_platform.models.validationitem1 import ValidationItem1, ValidationItem1TypedDict +class ValidationResult(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["errors", "warnings"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + ValidationResult + """ # noqa: E501 + errors: Optional[List[ValidationItem1]] = None + warnings: Optional[List[ValidationItem1]] = None + __properties: ClassVar[List[str]] = ["errors", "warnings"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - return m + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ValidationResult from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in errors (list) + _items = [] + if self.errors: + for _item_errors in self.errors: + if _item_errors: + _items.append(_item_errors.to_dict()) + _dict['errors'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in warnings (list) + _items = [] + if self.warnings: + for _item_warnings in self.warnings: + if _item_warnings: + _items.append(_item_warnings.to_dict()) + _dict['warnings'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ValidationResult from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "errors": [ValidationItem1.from_dict(_item) for _item in obj["errors"]] if obj.get("errors") is not None else None, + "warnings": [ValidationItem1.from_dict(_item) for _item in obj["warnings"]] if obj.get("warnings") is not None else None + }) + return _obj + + + + + +class ValidationResultTypedDict(TypedDict): + """TypedDict variant of ValidationResult, for dict-literal request/response inputs.""" + errors: NotRequired[Optional[List[ValidationItem1TypedDict]]] + warnings: NotRequired[Optional[List[ValidationItem1TypedDict]]] diff --git a/platform/src/codat_platform/models/shared/webhookconsumer.py b/platform/src/codat_platform/models/shared/webhookconsumer.py index 963af972d..ff7e021b2 100644 --- a/platform/src/codat_platform/models/shared/webhookconsumer.py +++ b/platform/src/codat_platform/models/shared/webhookconsumer.py @@ -1,91 +1,117 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated, NotRequired, TypedDict +from typing import Optional, Set +from typing_extensions import Self +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL +class WebhookConsumer(BaseModel): -class WebhookConsumerTypedDict(TypedDict): - r"""A webhook consumer is an HTTP endpoint that developers can configure to subscribe to Codat's supported event types. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'companyTags', 'company_tags'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + A webhook consumer is an HTTP endpoint that developers can configure to subscribe to Codat's supported event types. See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier for the webhook consumer.") + url: Optional[str] = Field(default=None, description="The URL that will consume webhook events dispatched by Codat.") + disabled: Optional[bool] = Field(default=False, description="Flag that enables or disables the endpoint from receiving events. Disabled when set to `true`.") + event_types: Optional[List[str]] = Field(default=None, description="An array of event types the webhook consumer subscribes to.", alias="eventTypes") + company_tags: OptionalNullable[List[str]] = Field(default=UNSET, description="Company tags provide an additional way to filter messages, independent of event types. Company tags are case-sensitive, and only messages from companies with matching tags will be sent to this endpoint. Use the format `tagKey:tagValue`.", alias="companyTags") + __properties: ClassVar[List[str]] = ["id", "url", "disabled", "eventTypes", "companyTags"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). - """ + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - company_tags: NotRequired[Nullable[List[str]]] - r"""Company tags provide an additional way to filter messages, independent of event types. Company tags are case-sensitive, and only messages from companies with matching tags will be sent to this endpoint. Use the format `tagKey:tagValue`.""" - disabled: NotRequired[Nullable[bool]] - r"""Flag that enables or disables the endpoint from receiving events. Disabled when set to `true`.""" - event_types: NotRequired[List[str]] - r"""An array of event types the webhook consumer subscribes to.""" - id: NotRequired[str] - r"""Unique identifier for the webhook consumer.""" - url: NotRequired[str] - r"""The URL that will consume webhook events dispatched by Codat.""" + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WebhookConsumer from a JSON string""" + return cls.from_dict(json.loads(json_str)) -class WebhookConsumer(BaseModel): - r"""A webhook consumer is an HTTP endpoint that developers can configure to subscribe to Codat's supported event types. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - """ + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - company_tags: Annotated[ - OptionalNullable[List[str]], pydantic.Field(alias="companyTags") - ] = UNSET - r"""Company tags provide an additional way to filter messages, independent of event types. Company tags are case-sensitive, and only messages from companies with matching tags will be sent to this endpoint. Use the format `tagKey:tagValue`.""" + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - disabled: OptionalNullable[bool] = False - r"""Flag that enables or disables the endpoint from receiving events. Disabled when set to `true`.""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WebhookConsumer from a dict""" + if obj is None: + return None - event_types: Annotated[Optional[List[str]], pydantic.Field(alias="eventTypes")] = ( - None - ) - r"""An array of event types the webhook consumer subscribes to.""" + if not isinstance(obj, dict): + return cls.model_validate(obj) - id: Optional[str] = None - r"""Unique identifier for the webhook consumer.""" + _obj = cls.model_validate({ + "id": obj.get("id"), + "url": obj.get("url"), + "disabled": obj.get("disabled") if obj.get("disabled") is not None else False, + "eventTypes": obj.get("eventTypes"), + "companyTags": obj.get("companyTags") + }) + return _obj - url: Optional[str] = None - r"""The URL that will consume webhook events dispatched by Codat.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["companyTags", "disabled", "eventTypes", "id", "url"]) - nullable_fields = set(["companyTags", "disabled"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - WebhookConsumer.model_rebuild() -except NameError: - pass + + + +class WebhookConsumerTypedDict(TypedDict): + """TypedDict variant of WebhookConsumer, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + url: NotRequired[Optional[str]] + disabled: NotRequired[Optional[bool]] + event_types: NotRequired[Optional[List[str]]] + company_tags: NotRequired[Optional[List[str]]] diff --git a/platform/src/codat_platform/models/shared/webhookconsumerprototype.py b/platform/src/codat_platform/models/shared/webhookconsumerprototype.py index 48d4ab0af..2962edd50 100644 --- a/platform/src/codat_platform/models/shared/webhookconsumerprototype.py +++ b/platform/src/codat_platform/models/shared/webhookconsumerprototype.py @@ -1,74 +1,114 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_platform.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class WebhookConsumerPrototypeTypedDict(TypedDict): - company_tags: NotRequired[Nullable[List[str]]] - r"""Company tags provide an additional way to filter messages, independent of event types. Company tags are case-sensitive, and only messages from companies with matching tags will be sent to this endpoint. Use the format `tagKey:tagValue`.""" - disabled: NotRequired[Nullable[bool]] - r"""Flag that enables or disables the endpoint from receiving events. Disabled when set to `true`.""" - event_types: NotRequired[List[str]] - r"""An array of event types the webhook consumer subscribes to.""" - url: NotRequired[str] - r"""The URL that will consume webhook events dispatched by Codat.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class WebhookConsumerPrototype(BaseModel): - company_tags: Annotated[ - OptionalNullable[List[str]], pydantic.Field(alias="companyTags") - ] = UNSET - r"""Company tags provide an additional way to filter messages, independent of event types. Company tags are case-sensitive, and only messages from companies with matching tags will be sent to this endpoint. Use the format `tagKey:tagValue`.""" - disabled: OptionalNullable[bool] = False - r"""Flag that enables or disables the endpoint from receiving events. Disabled when set to `true`.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - event_types: Annotated[Optional[List[str]], pydantic.Field(alias="eventTypes")] = ( - None - ) - r"""An array of event types the webhook consumer subscribes to.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from typing import Optional, Set +from typing_extensions import Self - url: Optional[str] = None - r"""The URL that will consume webhook events dispatched by Codat.""" +from codat_platform.types import OptionalNullable, UNSET, UNSET_SENTINEL +class WebhookConsumerPrototype(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["companyTags", "disabled", "eventTypes", "url"]) - nullable_fields = set(["companyTags", "disabled"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - WebhookConsumerPrototype.model_rebuild() -except NameError: - pass + _nullable = {'companyTags', 'company_tags'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + WebhookConsumerPrototype + """ # noqa: E501 + url: Optional[str] = Field(default=None, description="The URL that will consume webhook events dispatched by Codat.") + disabled: Optional[bool] = Field(default=False, description="Flag that enables or disables the endpoint from receiving events. Disabled when set to `true`.") + event_types: Optional[List[str]] = Field(default=None, description="An array of event types the webhook consumer subscribes to.", alias="eventTypes") + company_tags: OptionalNullable[List[str]] = Field(default=UNSET, description="Company tags provide an additional way to filter messages, independent of event types. Company tags are case-sensitive, and only messages from companies with matching tags will be sent to this endpoint. Use the format `tagKey:tagValue`.", alias="companyTags") + __properties: ClassVar[List[str]] = ["url", "disabled", "eventTypes", "companyTags"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WebhookConsumerPrototype from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WebhookConsumerPrototype from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "url": obj.get("url"), + "disabled": obj.get("disabled") if obj.get("disabled") is not None else False, + "eventTypes": obj.get("eventTypes"), + "companyTags": obj.get("companyTags") + }) + return _obj + + + + + +class WebhookConsumerPrototypeTypedDict(TypedDict): + """TypedDict variant of WebhookConsumerPrototype, for dict-literal request/response inputs.""" + url: NotRequired[Optional[str]] + disabled: NotRequired[Optional[bool]] + event_types: NotRequired[Optional[List[str]]] + company_tags: NotRequired[Optional[List[str]]] diff --git a/platform/src/codat_platform/models/shared/webhookconsumers.py b/platform/src/codat_platform/models/shared/webhookconsumers.py index cca3a9b1e..589164faa 100644 --- a/platform/src/codat_platform/models/shared/webhookconsumers.py +++ b/platform/src/codat_platform/models/shared/webhookconsumers.py @@ -1,32 +1,108 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .webhookconsumer import WebhookConsumer, WebhookConsumerTypedDict -from codat_platform.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import NotRequired, TypedDict +""" + Platform API + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | -class WebhookConsumersTypedDict(TypedDict): - results: NotRequired[List[WebhookConsumerTypedDict]] + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_platform.models.shared.webhookconsumer import WebhookConsumer, WebhookConsumerTypedDict +from typing import Optional, Set +from typing_extensions import Self class WebhookConsumers(BaseModel): - results: Optional[List[WebhookConsumer]] = None @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["results"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + WebhookConsumers + """ # noqa: E501 + results: Optional[List[WebhookConsumer]] = None + __properties: ClassVar[List[str]] = ["results"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WebhookConsumers from a JSON string""" + return cls.from_dict(json.loads(json_str)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - return m + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WebhookConsumers from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "results": [WebhookConsumer.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj + + + + + +class WebhookConsumersTypedDict(TypedDict): + """TypedDict variant of WebhookConsumers, for dict-literal request/response inputs.""" + results: NotRequired[Optional[List[WebhookConsumerTypedDict]]] diff --git a/platform/src/codat_platform/models/shared/writestatus.py b/platform/src/codat_platform/models/shared/writestatus.py index 829347fac..f8afe6d27 100644 --- a/platform/src/codat_platform/models/shared/writestatus.py +++ b/platform/src/codat_platform/models/shared/writestatus.py @@ -1,13 +1,39 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class WriteStatus(str, Enum): - r"""The current status of the write request, which is the same as the push operation status.""" + """ + The current status of the write request, which is the same as the push operation status. + """ + + """ + allowed enum values + """ + PENDING = 'Pending' + FAILED = 'Failed' + SUCCESS = 'Success' + TIMED_OUT = 'TimedOut' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of WriteStatus from a JSON string""" + return cls(json.loads(json_str)) + - PENDING = "Pending" - FAILED = "Failed" - SUCCESS = "Success" - TIMED_OUT = "TimedOut" diff --git a/platform/src/codat_platform/models/shared/writetype.py b/platform/src/codat_platform/models/shared/writetype.py index 90270e798..8195920d7 100644 --- a/platform/src/codat_platform/models/shared/writetype.py +++ b/platform/src/codat_platform/models/shared/writetype.py @@ -1,13 +1,39 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class WriteType(str, Enum): - r"""Type of write request.""" + """ + Type of write request. + """ + + """ + allowed enum values + """ + CREATE = 'Create' + UPDATE = 'Update' + DELETE = 'Delete' + UPLOAD_ATTACHMENT = 'UploadAttachment' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of WriteType from a JSON string""" + return cls(json.loads(json_str)) + - CREATE = "Create" - UPDATE = "Update" - DELETE = "Delete" - UPLOAD_ATTACHMENT = "UploadAttachment" diff --git a/platform/src/codat_platform/models/supplemental_data_source_configuration.py b/platform/src/codat_platform/models/supplemental_data_source_configuration.py new file mode 100644 index 000000000..bd311e62f --- /dev/null +++ b/platform/src/codat_platform/models/supplemental_data_source_configuration.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class SupplementalDataSourceConfiguration(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + The client's defined name for the object. + """ # noqa: E501 + data_source: Optional[str] = Field(default=None, description="The underlying endpoint of the source system which the configuration is targeting. ", alias="dataSource") + pull_data: Optional[Dict[str, str]] = Field(default=None, description="The additional properties that are required when pulling records.", alias="pullData") + push_data: Optional[Dict[str, str]] = Field(default=None, description="The additional properties that are required to create and/or update records.", alias="pushData") + __properties: ClassVar[List[str]] = ["dataSource", "pullData", "pushData"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SupplementalDataSourceConfiguration from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SupplementalDataSourceConfiguration from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "dataSource": obj.get("dataSource"), + "pullData": obj.get("pullData"), + "pushData": obj.get("pushData") + }) + return _obj + + + + + +class SupplementalDataSourceConfigurationTypedDict(TypedDict): + """TypedDict variant of SupplementalDataSourceConfiguration, for dict-literal request/response inputs.""" + data_source: NotRequired[Optional[str]] + pull_data: NotRequired[Optional[Dict[str, str]]] + push_data: NotRequired[Optional[Dict[str, str]]] diff --git a/platform/src/codat_platform/models/update_profile_sync_settings_request.py b/platform/src/codat_platform/models/update_profile_sync_settings_request.py new file mode 100644 index 000000000..c05d4ca9e --- /dev/null +++ b/platform/src/codat_platform/models/update_profile_sync_settings_request.py @@ -0,0 +1,121 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List +from codat_platform.models.shared.syncsetting import SyncSetting, SyncSettingTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class UpdateProfileSyncSettingsRequest(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + UpdateProfileSyncSettingsRequest + """ # noqa: E501 + client_id: str = Field(description="Unique identifier for your client in Codat.", alias="clientId") + settings: List[SyncSetting] + overrides_defaults: Optional[bool] = Field(default=True, description="Set to `True` if you want to override default [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings).", alias="overridesDefaults") + __properties: ClassVar[List[str]] = ["clientId", "settings", "overridesDefaults"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of UpdateProfileSyncSettingsRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in settings (list) + _items = [] + if self.settings: + for _item_settings in self.settings: + if _item_settings: + _items.append(_item_settings.to_dict()) + _dict['settings'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UpdateProfileSyncSettingsRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "clientId": obj.get("clientId"), + "settings": [SyncSetting.from_dict(_item) for _item in obj["settings"]] if obj.get("settings") is not None else None, + "overridesDefaults": obj.get("overridesDefaults") if obj.get("overridesDefaults") is not None else True + }) + return _obj + + + + +# Speakeasy compat alias — body class name collides with the +# request-wrapper class name; expose under the Speakeasy-style `Body` name. +UpdateProfileSyncSettingsRequestBody = UpdateProfileSyncSettingsRequest + + + +class UpdateProfileSyncSettingsRequestTypedDict(TypedDict): + """TypedDict variant of UpdateProfileSyncSettingsRequest, for dict-literal request/response inputs.""" + client_id: NotRequired[str] + settings: List[SyncSettingTypedDict] + overrides_defaults: NotRequired[bool] + +# Speakeasy TypedDict companions for response-class aliases. +UpdateProfileSyncSettingsRequestBodyTypedDict = UpdateProfileSyncSettingsRequestTypedDict diff --git a/platform/src/codat_platform/models/validation_item1.py b/platform/src/codat_platform/models/validation_item1.py new file mode 100644 index 000000000..c8da83588 --- /dev/null +++ b/platform/src/codat_platform/models/validation_item1.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class ValidationItem1(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + ValidationItem1 + """ # noqa: E501 + rule_id: Optional[str] = Field(default=None, description="The unique identifier of the rule that wasn't met.", alias="ruleId") + item_id: Optional[str] = Field(default=None, description="The unique identifier of the item that was validated.", alias="itemId") + message: Optional[str] = Field(default=None, description="The message that describes the validation warning or error.") + validator_name: Optional[str] = Field(default=None, description="The name of the validator that was used to validate the item.", alias="validatorName") + __properties: ClassVar[List[str]] = ["ruleId", "itemId", "message", "validatorName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ValidationItem1 from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ValidationItem1 from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "ruleId": obj.get("ruleId"), + "itemId": obj.get("itemId"), + "message": obj.get("message"), + "validatorName": obj.get("validatorName") + }) + return _obj + + + + + +class ValidationItem1TypedDict(TypedDict): + """TypedDict variant of ValidationItem1, for dict-literal request/response inputs.""" + rule_id: NotRequired[Optional[str]] + item_id: NotRequired[Optional[str]] + message: NotRequired[Optional[str]] + validator_name: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/models/validationitem1.py b/platform/src/codat_platform/models/validationitem1.py new file mode 100644 index 000000000..e338b1c9a --- /dev/null +++ b/platform/src/codat_platform/models/validationitem1.py @@ -0,0 +1,33 @@ +"""A validation item. Synthesized to match Speakeasy's shared surface.""" +from __future__ import annotations +from typing import Optional +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing_extensions import NotRequired, TypedDict + + +class ValidationItem1TypedDict(TypedDict): + item_id: NotRequired[Optional[str]] + message: NotRequired[Optional[str]] + rule_id: NotRequired[Optional[str]] + validator_name: NotRequired[Optional[str]] + + +class ValidationItem1(BaseModel): + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + def to_dict(self): + return self.model_dump(by_alias=True, exclude_none=True) + + @classmethod + def from_dict(cls, obj): + return cls.model_validate(obj) if obj is not None else None + + item_id: Optional[str] = Field(default=None, alias="itemId") + message: Optional[str] = None + rule_id: Optional[str] = Field(default=None, alias="ruleId") + validator_name: Optional[str] = Field(default=None, alias="validatorName") + + model_config = ConfigDict(populate_by_name=True, protected_namespaces=()) diff --git a/platform/src/codat_platform/models/webhook_zapier_key.py b/platform/src/codat_platform/models/webhook_zapier_key.py new file mode 100644 index 000000000..bb5a14f1d --- /dev/null +++ b/platform/src/codat_platform/models/webhook_zapier_key.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class WebhookZapierKey(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + WebhookZapierKey + """ # noqa: E501 + key: Optional[str] = Field(default=None, description="Integration key used to authorize Zapier's HTTP requests with Codat.") + __properties: ClassVar[List[str]] = ["key"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WebhookZapierKey from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WebhookZapierKey from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "key": obj.get("key") + }) + return _obj + + + + + +class WebhookZapierKeyTypedDict(TypedDict): + """TypedDict variant of WebhookZapierKey, for dict-literal request/response inputs.""" + key: NotRequired[Optional[str]] diff --git a/platform/src/codat_platform/push_data.py b/platform/src/codat_platform/push_data.py index a2a3201f1..ea2c4b307 100644 --- a/platform/src/codat_platform/push_data.py +++ b/platform/src/codat_platform/push_data.py @@ -1,621 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.push_data — re-export of the push_data method group.""" -from .basesdk import BaseSDK -from codat_platform import utils -from codat_platform._hooks import HookContext -from codat_platform.models import errors, operations, shared -from codat_platform.types import BaseModel, OptionalNullable, UNSET -from codat_platform.utils.unmarshal_json_response import unmarshal_json_response -from typing import Any, Mapping, Optional, Union, cast - - -class PushData(BaseSDK): - r"""Initiate and monitor Create, Update, and Delete operations.""" - - def get_model_options( - self, - *, - request: Union[ - operations.GetCreateUpdateModelOptionsByDataTypeRequest, - operations.GetCreateUpdateModelOptionsByDataTypeRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOption: - r"""Get push options - - This is the generic documentation for creation and updating of data. See the equivalent endpoint for a given data type for more specific information. - - Before pushing data into accounting software, it is often necessary to collect some details from the user as to how they would like the data to be inserted. This includes names and amounts on transactional entities, but also factors such as categorisation of entities, which is often handled differently between different accounting software. A good example of this is specifying where on the balance sheet/profit and loss reports the user would like a newly-created nominal account to appear. - - Codat tries not to limit users to pushing to a very limited number of standard categories, so we have implemented \"options\" endpoints, which allow us to expose to our clients the fields which are required to be pushed for a specific linked company, and the options which may be selected for each field. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetCreateUpdateModelOptionsByDataTypeRequest - ) - request = cast(operations.GetCreateUpdateModelOptionsByDataTypeRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/options/{dataType}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-create-update-model-options-by-data-type", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PushOption, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_model_options_async( - self, - *, - request: Union[ - operations.GetCreateUpdateModelOptionsByDataTypeRequest, - operations.GetCreateUpdateModelOptionsByDataTypeRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOption: - r"""Get push options - - This is the generic documentation for creation and updating of data. See the equivalent endpoint for a given data type for more specific information. - - Before pushing data into accounting software, it is often necessary to collect some details from the user as to how they would like the data to be inserted. This includes names and amounts on transactional entities, but also factors such as categorisation of entities, which is often handled differently between different accounting software. A good example of this is specifying where on the balance sheet/profit and loss reports the user would like a newly-created nominal account to appear. - - Codat tries not to limit users to pushing to a very limited number of standard categories, so we have implemented \"options\" endpoints, which allow us to expose to our clients the fields which are required to be pushed for a specific linked company, and the options which may be selected for each field. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetCreateUpdateModelOptionsByDataTypeRequest - ) - request = cast(operations.GetCreateUpdateModelOptionsByDataTypeRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/options/{dataType}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-create-update-model-options-by-data-type", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PushOption, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get_operation( - self, - *, - request: Union[ - operations.GetPushOperationRequest, - operations.GetPushOperationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOperation: - r"""Get push operation - - The **Get push operation** endpoint returns a specific [push operation](/using-the-api/push) identified by the `pushOperationKey` that was performed on the company. - - Write operations are actions that send requests to Codat, enabling the creation, updating, deletion of records, or uploading attachments in the connected accounting software. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetPushOperationRequest) - request = cast(operations.GetPushOperationRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/push/{pushOperationKey}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-push-operation", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PushOperation, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_operation_async( - self, - *, - request: Union[ - operations.GetPushOperationRequest, - operations.GetPushOperationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOperation: - r"""Get push operation - - The **Get push operation** endpoint returns a specific [push operation](/using-the-api/push) identified by the `pushOperationKey` that was performed on the company. - - Write operations are actions that send requests to Codat, enabling the creation, updating, deletion of records, or uploading attachments in the connected accounting software. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetPushOperationRequest) - request = cast(operations.GetPushOperationRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/push/{pushOperationKey}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-push-operation", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PushOperation, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def list_operations( - self, - *, - request: Union[ - operations.GetCompanyPushHistoryRequest, - operations.GetCompanyPushHistoryRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOperations: - r"""List push operations - - The **List push operations** endpoint returns a list of [push operations](/using-the-api/push) performed on the company. - - Write operations are actions that send requests to Codat, enabling the creation, updating, deletion of records, or uploading attachments in the connected accounting software. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanyPushHistoryRequest) - request = cast(operations.GetCompanyPushHistoryRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/push", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company-push-history", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PushOperations, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def list_operations_async( - self, - *, - request: Union[ - operations.GetCompanyPushHistoryRequest, - operations.GetCompanyPushHistoryRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOperations: - r"""List push operations - - The **List push operations** endpoint returns a list of [push operations](/using-the-api/push) performed on the company. - - Write operations are actions that send requests to Codat, enabling the creation, updating, deletion of records, or uploading attachments in the connected accounting software. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanyPushHistoryRequest) - request = cast(operations.GetCompanyPushHistoryRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/push", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company-push-history", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PushOperations, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_platform.api.push_data import PushData diff --git a/platform/src/codat_platform/py.typed b/platform/src/codat_platform/py.typed index 3e38f1a92..e69de29bb 100644 --- a/platform/src/codat_platform/py.typed +++ b/platform/src/codat_platform/py.typed @@ -1 +0,0 @@ -# Marker file for PEP 561. The package enables type hints. diff --git a/platform/src/codat_platform/read_data.py b/platform/src/codat_platform/read_data.py index decffd016..d971c2bfb 100644 --- a/platform/src/codat_platform/read_data.py +++ b/platform/src/codat_platform/read_data.py @@ -1,223 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.read_data — re-export of the read_data method group.""" -from .basesdk import BaseSDK -from codat_platform import utils -from codat_platform._hooks import HookContext -from codat_platform.models import errors, operations, shared -from codat_platform.types import BaseModel, OptionalNullable, UNSET -from codat_platform.utils.unmarshal_json_response import unmarshal_json_response -from typing import Any, Mapping, Optional, Union, cast - - -class ReadData(BaseSDK): - r"""View validation outcomes for completed read data operations.""" - - def get_validation_results( - self, - *, - request: Union[ - operations.GetReadValidationResultsRequest, - operations.GetReadValidationResultsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ValidationResult: - r"""Get validation results - - Use the **Get validation results** endpoint to review warnings and errors encountered during the data type validation phase. - - The validation result [schema](https://docs.codat.io/platform-api#/schemas/ValidationResult) contains two message arrays: - - - **`warnings`** array lists potential issues with the data type that may require attention but don't block usage. - - **`errors`** array contains critical issues that must be resolved before the data type can be used. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetReadValidationResultsRequest - ) - request = cast(operations.GetReadValidationResultsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/sync/{datasetId}/validation", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-read-validation-results", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.ValidationResult, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_validation_results_async( - self, - *, - request: Union[ - operations.GetReadValidationResultsRequest, - operations.GetReadValidationResultsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ValidationResult: - r"""Get validation results - - Use the **Get validation results** endpoint to review warnings and errors encountered during the data type validation phase. - - The validation result [schema](https://docs.codat.io/platform-api#/schemas/ValidationResult) contains two message arrays: - - - **`warnings`** array lists potential issues with the data type that may require attention but don't block usage. - - **`errors`** array contains critical issues that must be resolved before the data type can be used. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetReadValidationResultsRequest - ) - request = cast(operations.GetReadValidationResultsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/sync/{datasetId}/validation", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-read-validation-results", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.ValidationResult, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_platform.api.read_data import ReadData diff --git a/platform/src/codat_platform/refresh_data.py b/platform/src/codat_platform/refresh_data.py index 804347ccc..ca5271947 100644 --- a/platform/src/codat_platform/refresh_data.py +++ b/platform/src/codat_platform/refresh_data.py @@ -1,1005 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.refresh_data — re-export of the refresh_data method group.""" -from .basesdk import BaseSDK -from codat_platform import utils -from codat_platform._hooks import HookContext -from codat_platform.models import errors, operations, shared -from codat_platform.types import BaseModel, OptionalNullable, UNSET -from codat_platform.utils.unmarshal_json_response import unmarshal_json_response -from typing import Any, Mapping, Optional, Union, cast - - -class RefreshData(BaseSDK): - r"""Initiate data refreshes, view pull status and history.""" - - def all( - self, - *, - request: Union[ - operations.RefreshCompanyDataRequest, - operations.RefreshCompanyDataRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Refresh all data - - Refreshes all data types with `fetch on first link` set to `true` for a given company. - - This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. - - [Read more](https://docs.codat.io/core-concepts/data-type-settings) about data type settings and `fetch on first link`. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.RefreshCompanyDataRequest) - request = cast(operations.RefreshCompanyDataRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/data/all", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="refresh-company-data", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def all_async( - self, - *, - request: Union[ - operations.RefreshCompanyDataRequest, - operations.RefreshCompanyDataRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Refresh all data - - Refreshes all data types with `fetch on first link` set to `true` for a given company. - - This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. - - [Read more](https://docs.codat.io/core-concepts/data-type-settings) about data type settings and `fetch on first link`. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.RefreshCompanyDataRequest) - request = cast(operations.RefreshCompanyDataRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/data/all", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="refresh-company-data", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def by_data_type( - self, - *, - request: Union[ - operations.RefreshDataTypeRequest, - operations.RefreshDataTypeRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperation: - r"""Refresh data type - - Refreshes a given data type for a given company. - - This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.RefreshDataTypeRequest) - request = cast(operations.RefreshDataTypeRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/data/queue/{dataType}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="refresh-data-type", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PullOperation, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def by_data_type_async( - self, - *, - request: Union[ - operations.RefreshDataTypeRequest, - operations.RefreshDataTypeRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperation: - r"""Refresh data type - - Refreshes a given data type for a given company. - - This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.RefreshDataTypeRequest) - request = cast(operations.RefreshDataTypeRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/data/queue/{dataType}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="refresh-data-type", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PullOperation, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get( - self, - *, - request: Union[ - operations.GetCompanyDataStatusRequest, - operations.GetCompanyDataStatusRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.DataStatuses: - r"""Get data status - - Get the state of each data type for a company - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanyDataStatusRequest) - request = cast(operations.GetCompanyDataStatusRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/dataStatus", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company-data-status", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.DataStatuses, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_async( - self, - *, - request: Union[ - operations.GetCompanyDataStatusRequest, - operations.GetCompanyDataStatusRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.DataStatuses: - r"""Get data status - - Get the state of each data type for a company - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanyDataStatusRequest) - request = cast(operations.GetCompanyDataStatusRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/dataStatus", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company-data-status", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.DataStatuses, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get_pull_operation( - self, - *, - request: Union[ - operations.GetPullOperationRequest, - operations.GetPullOperationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperation: - r"""Get pull operation - - Retrieve information about a single dataset or pull operation. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetPullOperationRequest) - request = cast(operations.GetPullOperationRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/data/history/{datasetId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-pull-operation", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PullOperation, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_pull_operation_async( - self, - *, - request: Union[ - operations.GetPullOperationRequest, - operations.GetPullOperationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperation: - r"""Get pull operation - - Retrieve information about a single dataset or pull operation. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetPullOperationRequest) - request = cast(operations.GetPullOperationRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/data/history/{datasetId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-pull-operation", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PullOperation, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def list_pull_operations( - self, - *, - request: Union[ - operations.ListPullOperationsRequest, - operations.ListPullOperationsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperations: - r"""List pull operations - - Gets the pull operation history (datasets) for a given company. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListPullOperationsRequest) - request = cast(operations.ListPullOperationsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/data/history", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-pull-operations", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PullOperations, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def list_pull_operations_async( - self, - *, - request: Union[ - operations.ListPullOperationsRequest, - operations.ListPullOperationsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperations: - r"""List pull operations - - Gets the pull operation history (datasets) for a given company. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListPullOperationsRequest) - request = cast(operations.ListPullOperationsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/data/history", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-pull-operations", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PullOperations, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_platform.api.refresh_data import RefreshData diff --git a/platform/src/codat_platform/rest.py b/platform/src/codat_platform/rest.py new file mode 100644 index 000000000..5e6743af2 --- /dev/null +++ b/platform/src/codat_platform/rest.py @@ -0,0 +1,258 @@ +# coding: utf-8 + +""" + Platform API + + An API for the common components of all of Codat's products. These end points cover creating and managing your companies, data connections, and integrations. [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Connection management | Configure connection management UI and retrieve access tokens for authentication. | | Webhooks | Create and manage webhooks that listen to Codat's events. | | Integrations | Get a list of integrations supported by Codat and their logos. | | Refresh data | Initiate data refreshes, view pull status and history. | | Settings | Manage company profile configuration, sync settings, and API keys. | | Push data | Initiate and monitor Create, Update, and Delete operations. | | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import json +import re +import ssl + +import urllib3 + +from codat_platform.exceptions import ApiException, ApiValueError + +SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"} +RESTResponseType = urllib3.HTTPResponse + + +def is_socks_proxy_url(url): + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES + + +class RESTResponse(io.IOBase): + + def __init__(self, resp) -> None: + self.response = resp + self.status = resp.status + self.reason = resp.reason + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.data + return self.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.response.headers.get(name, default) + + +class RESTClientObject: + + def __init__(self, configuration) -> None: + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + pool_args = { + "cert_reqs": cert_reqs, + "ca_certs": configuration.ssl_ca_cert, + "cert_file": configuration.cert_file, + "key_file": configuration.key_file, + } + if configuration.assert_hostname is not None: + pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) + + if configuration.retries is not None: + pool_args['retries'] = configuration.retries + + if configuration.tls_server_name: + pool_args['server_hostname'] = configuration.tls_server_name + + + if configuration.socket_options is not None: + pool_args['socket_options'] = configuration.socket_options + + if configuration.connection_pool_maxsize is not None: + pool_args['maxsize'] = configuration.connection_pool_maxsize + + # https pool manager + self.pool_manager: urllib3.PoolManager + + if configuration.proxy: + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + pool_args["proxy_url"] = configuration.proxy + pool_args["headers"] = configuration.proxy_headers + self.pool_manager = SOCKSProxyManager(**pool_args) + else: + pool_args["proxy_url"] = configuration.proxy + pool_args["proxy_headers"] = configuration.proxy_headers + self.pool_manager = urllib3.ProxyManager(**pool_args) + else: + self.pool_manager = urllib3.PoolManager(**pool_args) + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): + """Perform requests. + + :param method: http request method + :param url: http request url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, float)): + timeout = urllib3.Timeout(total=_request_timeout) + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): + timeout = urllib3.Timeout( + connect=_request_timeout[0], + read=_request_timeout[1] + ) + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + + # no content type provided or payload is json + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, + url, + body=request_body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'application/x-www-form-urlencoded': + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=False, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers['Content-Type'] + # Ensures that dict objects are serialized + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=True, + timeout=timeout, + headers=headers, + preload_content=False + ) + # Pass a `string` parameter directly in the body to support + # other content types than JSON when `body` argument is + # provided in serialized form. + elif isinstance(body, str) or isinstance(body, bytes): + r = self.pool_manager.request( + method, + url, + body=body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif headers['Content-Type'].startswith('text/') and isinstance(body, bool): + request_body = "true" if body else "false" + r = self.pool_manager.request( + method, + url, + body=request_body, + preload_content=False, + timeout=timeout, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request( + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False + ) + except urllib3.exceptions.SSLError as e: + msg = "\n".join([type(e).__name__, str(e)]) + raise ApiException(status=0, reason=msg) + + return RESTResponse(r) diff --git a/platform/src/codat_platform/sdk.py b/platform/src/codat_platform/sdk.py index 144605432..f257ebfbe 100644 --- a/platform/src/codat_platform/sdk.py +++ b/platform/src/codat_platform/sdk.py @@ -1,107 +1,91 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from .basesdk import BaseSDK -from .httpclient import AsyncHttpClient, ClientOwner, HttpClient, close_clients -from .sdkconfiguration import SDKConfiguration -from .utils.logger import Logger, get_default_logger -from .utils.retries import RetryConfig -from codat_platform import utils -from codat_platform._hooks import SDKHooks -from codat_platform.models import shared -from codat_platform.types import OptionalNullable, UNSET -import httpx -import importlib -import sys -from typing import Callable, Dict, Optional, TYPE_CHECKING, Union, cast -import weakref +"""Top-level composed client for Platform API. + +Generated by pipeline/postprocess_generated.py — do not edit by hand. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Callable, Dict, Mapping, Optional, Union + +from codat_platform.api_client import ApiClient +from codat_platform.configuration import Configuration +from codat_platform._hooks import SDKHooks, attach_hooks_to_api_client +from codat_platform.types import UNSET, OptionalNullable +from codat_platform.utils.retries import RetryConfig if TYPE_CHECKING: - from codat_platform.companies import Companies - from codat_platform.connection_management import ConnectionManagement - from codat_platform.connections import Connections - from codat_platform.cors import Cors - from codat_platform.custom_data_type import CustomDataType - from codat_platform.integrations import Integrations - from codat_platform.push_data import PushData - from codat_platform.read_data import ReadData - from codat_platform.refresh_data import RefreshData - from codat_platform.settings import Settings - from codat_platform.supplemental_data import SupplementalData - from codat_platform.webhooks import Webhooks - - -class CodatPlatform(BaseSDK): - r"""Platform API: Platform API - - An API for the common components of all of Codat's products. - - These end points cover creating and managing your companies, data connections, and integrations. - - [Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) - - --- - - ## Endpoints - - | Endpoints | Description | - | :- |:- | - | Companies | Create and manage your SMB users' companies. | - | Connections | Create new and manage existing data connections for a company. | - | Connection management | Configure connection management UI and retrieve access tokens for authentication. | - | Webhooks | Create and manage webhooks that listen to Codat's events. | - | Integrations | Get a list of integrations supported by Codat and their logos. | - | Refresh data | Initiate data refreshes, view pull status and history. | - | Settings | Manage company profile configuration, sync settings, and API keys. | - | Push data | Initiate and monitor Create, Update, and Delete operations. | - | Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | - | Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | - - """ + from codat_platform.httpclient import AsyncHttpClient, HttpClient + +from codat_platform.api.cors import Cors +from codat_platform.api.companies import Companies +from codat_platform.api.connection_management import ConnectionManagement +from codat_platform.api.connections import Connections +from codat_platform.api.webhooks import Webhooks +from codat_platform.api.integrations import Integrations +from codat_platform.api.refresh_data import RefreshData +from codat_platform.api.settings import Settings +from codat_platform.api.push_data import PushData +from codat_platform.api.read_data import ReadData +from codat_platform.api.supplemental_data import SupplementalData +from codat_platform.api.custom_data_type import CustomDataType + + +_DEFAULT_TIMEOUT_MS = 5000 + + +class CodatPlatform: + r"""Platform API: An API for the common components of all of Codat's products. + +These end points cover creating and managing your companies, data connections, and integrations. + +[Read about the building blocks of Codat...](https://docs.codat.io/core-concepts/companies) | [See our OpenAPI spec](https://github.com/codatio/oas) + +--- + +## Endpoints + +| Endpoints | Description | +| :- |:- | +| Companies | Create and manage your SMB users' companies. | +| Connections | Create new and manage existing data connections for a company. | +| Connection management | Configure connection management UI and retrieve access tokens for authentication. | +| Webhooks | Create and manage webhooks that listen to Codat's events. | +| Integrations | Get a list of integrations supported by Codat and their logos. | +| Refresh data | Initiate data refreshes, view pull status and history. | +| Settings | Manage company profile configuration, sync settings, and API keys. | +| Push data | Initiate and monitor Create, Update, and Delete operations. | +| Supplemental data | Configure and pull additional data you can include in Codat's standard data types. | +| Custom data type | Configure and pull additional data types that are not included in Codat's standardized data model. | +""" - settings: "Settings" - r"""Manage company profile configuration, sync settings, and API keys.""" + cors: "Cors" + r"""""" companies: "Companies" r"""Create and manage your SMB users' companies.""" connection_management: "ConnectionManagement" r"""Configure UI and retrieve access tokens for authentication used by **Connections SDK**.""" connections: "Connections" r"""Create new and manage existing data connections for a company.""" - custom_data_type: "CustomDataType" - r"""Configure and pull additional data types that are not included in Codat's standardized data model.""" - push_data: "PushData" - r"""Initiate and monitor Create, Update, and Delete operations.""" + webhooks: "Webhooks" + r"""Create and manage webhooks that listen to Codat's events.""" + integrations: "Integrations" + r"""Get a list of integrations supported by Codat and their logos.""" refresh_data: "RefreshData" r"""Initiate data refreshes, view pull status and history.""" + settings: "Settings" + r"""Manage company profile configuration, sync settings, and API keys.""" + push_data: "PushData" + r"""Initiate and monitor Create, Update, and Delete operations.""" read_data: "ReadData" r"""View validation outcomes for completed read data operations.""" - cors: "Cors" - integrations: "Integrations" - r"""Get a list of integrations supported by Codat and their logos.""" supplemental_data: "SupplementalData" r"""Configure and pull additional data you can include in Codat's standard data types.""" - webhooks: "Webhooks" - r"""Create and manage webhooks that listen to Codat's events.""" - _sub_sdk_map = { - "settings": ("codat_platform.settings", "Settings"), - "companies": ("codat_platform.companies", "Companies"), - "connection_management": ( - "codat_platform.connection_management", - "ConnectionManagement", - ), - "connections": ("codat_platform.connections", "Connections"), - "custom_data_type": ("codat_platform.custom_data_type", "CustomDataType"), - "push_data": ("codat_platform.push_data", "PushData"), - "refresh_data": ("codat_platform.refresh_data", "RefreshData"), - "read_data": ("codat_platform.read_data", "ReadData"), - "cors": ("codat_platform.cors", "Cors"), - "integrations": ("codat_platform.integrations", "Integrations"), - "supplemental_data": ("codat_platform.supplemental_data", "SupplementalData"), - "webhooks": ("codat_platform.webhooks", "Webhooks"), - } + custom_data_type: "CustomDataType" + r"""Configure and pull additional data types that are not included in Codat's standardized data model.""" def __init__( self, - security: Union[shared.Security, Callable[[], shared.Security]], + security: Optional[Any] = None, server_idx: Optional[int] = None, url_params: Optional[Dict[str, str]] = None, server_url: Optional[str] = None, @@ -109,139 +93,98 @@ def __init__( async_client: Optional[AsyncHttpClient] = None, retry_config: OptionalNullable[RetryConfig] = UNSET, timeout_ms: Optional[int] = None, - debug_logger: Optional[Logger] = None, + debug_logger: Optional[Any] = None, ) -> None: - r"""Instantiates the SDK configuring it with the provided parameters. - - :param security: The security details required for authentication - :param server_idx: The index of the server to use for all methods - :param server_url: The server URL to use for all methods - :param url_params: Parameters to optionally template the server URL with - :param client: The HTTP client to use for all synchronous methods - :param async_client: The Async HTTP client to use for all asynchronous methods - :param retry_config: The retry configuration to use for all supported methods - :param timeout_ms: Optional request timeout applied to each operation in milliseconds - """ - client_supplied = True - if client is None: - client = httpx.Client(follow_redirects=True) - client_supplied = False - - assert issubclass( - type(client), HttpClient - ), "The provided client must implement the HttpClient protocol." - - async_client_supplied = True - if async_client is None: - async_client = httpx.AsyncClient(follow_redirects=True) - async_client_supplied = False - - if debug_logger is None: - debug_logger = get_default_logger() - - assert issubclass( - type(async_client), AsyncHttpClient - ), "The provided async_client must implement the AsyncHttpClient protocol." - - if server_url is not None: - if url_params is not None: - server_url = utils.template_url(server_url, url_params) - - BaseSDK.__init__( - self, - SDKConfiguration( - client=client, - client_supplied=client_supplied, - async_client=async_client, - async_client_supplied=async_client_supplied, - security=security, - server_url=server_url, - server_idx=server_idx, - retry_config=retry_config, - timeout_ms=timeout_ms, - debug_logger=debug_logger, - ), - parent_ref=self, + self._security = security + self._retry_config = retry_config + self._timeout_ms = timeout_ms + self._debug_logger = debug_logger + if async_client is not None: + import warnings as _w + _w.warn( + "the async_client kwarg is accepted for Speakeasy-SDK compatibility " + "but not used: the bare async methods (e.g. .companies.list_async(...)) " + "run the sync stack in a worker thread, where an httpx.AsyncClient " + "cannot be driven safely. Pass client= (an httpx.Client) instead — it " + "carries every request, including the *_async methods.", + stacklevel=2, + ) + + config = Configuration(host=server_url) if server_url else Configuration() + self._api_client = ApiClient(configuration=config) + if client is not None: + from codat_platform._httpx_transport import HttpxRestClient + self._api_client.rest_client = HttpxRestClient(client) + try: + from codat_platform._version import __user_agent__ as _ua + self._api_client.set_default_header("User-Agent", _ua) + except Exception: + pass + self._hooks = SDKHooks() + attach_hooks_to_api_client( + self._api_client, + self._hooks, + base_url=(server_url or ""), + security_source=security, + auth_headers=[('auth_header', 'Authorization')], ) - hooks = SDKHooks() - - # pylint: disable=protected-access - self.sdk_configuration.__dict__["_hooks"] = hooks - - current_server_url, *_ = self.sdk_configuration.get_server_details() - server_url, self.sdk_configuration.client = hooks.sdk_init( - current_server_url, client - ) - if current_server_url != server_url: - self.sdk_configuration.server_url = server_url - - weakref.finalize( - self, - close_clients, - cast(ClientOwner, self.sdk_configuration), - self.sdk_configuration.client, - self.sdk_configuration.client_supplied, - self.sdk_configuration.async_client, - self.sdk_configuration.async_client_supplied, - ) - - def dynamic_import(self, modname, retries=3): - for attempt in range(retries): - try: - return importlib.import_module(modname) - except KeyError: - # Clear any half-initialized module and retry - sys.modules.pop(modname, None) - if attempt == retries - 1: - break - raise KeyError(f"Failed to import module '{modname}' after {retries} attempts") - - def __getattr__(self, name: str): - if name in self._sub_sdk_map: - module_path, class_name = self._sub_sdk_map[name] - try: - module = self.dynamic_import(module_path) - klass = getattr(module, class_name) - instance = klass(self.sdk_configuration, parent_ref=self) - setattr(self, name, instance) - return instance - except ImportError as e: - raise AttributeError( - f"Failed to import module {module_path} for attribute {name}: {e}" - ) from e - except AttributeError as e: - raise AttributeError( - f"Failed to find class {class_name} in module {module_path} for attribute {name}: {e}" - ) from e - - raise AttributeError( - f"'{type(self).__name__}' object has no attribute '{name}'" - ) - - def __dir__(self): - default_attrs = list(super().__dir__()) - lazy_attrs = list(self._sub_sdk_map.keys()) - return sorted(list(set(default_attrs + lazy_attrs))) + self.cors = Cors(api_client=self._api_client) + self.companies = Companies(api_client=self._api_client) + self.connection_management = ConnectionManagement(api_client=self._api_client) + self.connections = Connections(api_client=self._api_client) + self.webhooks = Webhooks(api_client=self._api_client) + self.integrations = Integrations(api_client=self._api_client) + self.refresh_data = RefreshData(api_client=self._api_client) + self.settings = Settings(api_client=self._api_client) + self.push_data = PushData(api_client=self._api_client) + self.read_data = ReadData(api_client=self._api_client) + self.supplemental_data = SupplementalData(api_client=self._api_client) + self.custom_data_type = CustomDataType(api_client=self._api_client) + + # Attach the SDK-level retry + timeout defaults to each method-group so a + # per-call retries=UNSET / timeout_ms=None falls back to them. When no + # timeout_ms is set the default is _DEFAULT_TIMEOUT_MS (matches the shipped SDK). + _sdk_retry_default = retry_config if not isinstance(retry_config, type(UNSET)) else None + _sdk_timeout_default = timeout_ms if timeout_ms is not None else _DEFAULT_TIMEOUT_MS + _group_api_prefix = type(self).__module__.rsplit(".", 1)[0] + ".api." + _defaults_seen: set = set() + + def _attach_sdk_defaults(_grp) -> None: + if id(_grp) in _defaults_seen: + return + _defaults_seen.add(id(_grp)) + object.__setattr__(_grp, "_sdk_retry_config", _sdk_retry_default) + object.__setattr__(_grp, "_sdk_timeout_ms", _sdk_timeout_default) + for _name, _child in list(vars(_grp).items()): + if not _name.startswith("_") and type(_child).__module__.startswith(_group_api_prefix): + _attach_sdk_defaults(_child) + + for _grp in ( + self.cors, + self.companies, + self.connection_management, + self.connections, + self.webhooks, + self.integrations, + self.refresh_data, + self.settings, + self.push_data, + self.read_data, + self.supplemental_data, + self.custom_data_type, + ): + _attach_sdk_defaults(_grp) - def __enter__(self): + def __enter__(self) -> "CodatPlatform": + self._api_client.__enter__() return self - async def __aenter__(self): - return self + def __exit__(self, exc_type, exc, tb) -> None: + self._api_client.__exit__(exc_type, exc, tb) - def __exit__(self, exc_type, exc_val, exc_tb): - if ( - self.sdk_configuration.client is not None - and not self.sdk_configuration.client_supplied - ): - self.sdk_configuration.client.close() - self.sdk_configuration.client = None + async def __aenter__(self) -> "CodatPlatform": + return self - async def __aexit__(self, exc_type, exc_val, exc_tb): - if ( - self.sdk_configuration.async_client is not None - and not self.sdk_configuration.async_client_supplied - ): - await self.sdk_configuration.async_client.aclose() - self.sdk_configuration.async_client = None + async def __aexit__(self, exc_type, exc, tb) -> None: + self._api_client.__exit__(exc_type, exc, tb) diff --git a/platform/src/codat_platform/sdkconfiguration.py b/platform/src/codat_platform/sdkconfiguration.py deleted file mode 100644 index f7207f800..000000000 --- a/platform/src/codat_platform/sdkconfiguration.py +++ /dev/null @@ -1,49 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from ._version import ( - __gen_version__, - __openapi_doc_version__, - __user_agent__, - __version__, -) -from .httpclient import AsyncHttpClient, HttpClient -from .utils import Logger, RetryConfig, remove_suffix -from codat_platform.models import shared -from codat_platform.types import OptionalNullable, UNSET -from dataclasses import dataclass -from pydantic import Field -from typing import Callable, Dict, Optional, Tuple, Union - - -SERVERS = [ - "https://api.codat.io", - # Production -] -"""Contains the list of servers available to the SDK""" - - -@dataclass -class SDKConfiguration: - client: Union[HttpClient, None] - client_supplied: bool - async_client: Union[AsyncHttpClient, None] - async_client_supplied: bool - debug_logger: Logger - security: Optional[Union[shared.Security, Callable[[], shared.Security]]] = None - server_url: Optional[str] = "" - server_idx: Optional[int] = 0 - language: str = "python" - openapi_doc_version: str = __openapi_doc_version__ - sdk_version: str = __version__ - gen_version: str = __gen_version__ - user_agent: str = __user_agent__ - retry_config: OptionalNullable[RetryConfig] = Field(default_factory=lambda: UNSET) - timeout_ms: Optional[int] = None - - def get_server_details(self) -> Tuple[str, Dict[str, str]]: - if self.server_url is not None and self.server_url: - return remove_suffix(self.server_url, "/"), {} - if self.server_idx is None: - self.server_idx = 0 - - return SERVERS[self.server_idx], {} diff --git a/platform/src/codat_platform/settings.py b/platform/src/codat_platform/settings.py index bc87d0f93..e1cf15d3d 100644 --- a/platform/src/codat_platform/settings.py +++ b/platform/src/codat_platform/settings.py @@ -1,1809 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.settings — re-export of the settings method group.""" -from .basesdk import BaseSDK -from codat_platform import utils -from codat_platform._hooks import HookContext -from codat_platform.models import errors, operations, shared -from codat_platform.types import BaseModel, OptionalNullable, UNSET -from codat_platform.utils.unmarshal_json_response import unmarshal_json_response -from typing import Any, Mapping, Optional, Union, cast - - -class Settings(BaseSDK): - r"""Manage company profile configuration, sync settings, and API keys.""" - - def create_api_key( - self, - *, - request: Optional[ - Union[shared.CreateAPIKey, shared.CreateAPIKeyTypedDict] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.APIKeyDetails: - r"""Create API key - - Use the *Create API keys* endpoint to generate a new API key for your client. - - [API keys](https://docs.codat.io/platform-api#/schemas/apiKeys) are tokens used to control access to the API. Include this token in the `Authorization` header parameter when making API calls, following the word \"Basic\" and a space with your API key. - - You can [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat and managing API keys via the Portal UI or API. - - ### Tips and pitfalls - - * Your first API key is created for you. Access this key via [Codat's Portal](https://app.codat.io/developers/api-keys). - * If you require multiple API keys, perform multiple calls to the *Create API keys* endpoint. - * The number of API keys is limited to 10. If you have reached the maximum amount of keys, use the *Delete API key* endpoint to delete an unused key first. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, Optional[shared.CreateAPIKey]) - request = cast(Optional[shared.CreateAPIKey], request) - - req = self._build_request( - method="POST", - path="/apiKeys", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, False, True, "json", Optional[shared.CreateAPIKey] - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-api-key", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.APIKeyDetails, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "409", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def create_api_key_async( - self, - *, - request: Optional[ - Union[shared.CreateAPIKey, shared.CreateAPIKeyTypedDict] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.APIKeyDetails: - r"""Create API key - - Use the *Create API keys* endpoint to generate a new API key for your client. - - [API keys](https://docs.codat.io/platform-api#/schemas/apiKeys) are tokens used to control access to the API. Include this token in the `Authorization` header parameter when making API calls, following the word \"Basic\" and a space with your API key. - - You can [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat and managing API keys via the Portal UI or API. - - ### Tips and pitfalls - - * Your first API key is created for you. Access this key via [Codat's Portal](https://app.codat.io/developers/api-keys). - * If you require multiple API keys, perform multiple calls to the *Create API keys* endpoint. - * The number of API keys is limited to 10. If you have reached the maximum amount of keys, use the *Delete API key* endpoint to delete an unused key first. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, Optional[shared.CreateAPIKey]) - request = cast(Optional[shared.CreateAPIKey], request) - - req = self._build_request_async( - method="POST", - path="/apiKeys", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, False, True, "json", Optional[shared.CreateAPIKey] - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-api-key", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.APIKeyDetails, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "409", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def delete_api_key( - self, - *, - request: Union[ - operations.DeleteAPIKeyRequest, operations.DeleteAPIKeyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ErrorMessage: - r"""Delete API key - - Use the *Delete API keys* endpoint to delete an existing API key, providing its valid `id` as a parameter. Note that this operation is not reversible. - - [API keys](https://docs.codat.io/platform-api#/schemas/apiKeys) are tokens used to control access to the API. Include this token in the `Authorization` header parameter when making API calls, following the word \"Basic\" and a space with your API key. - - You can [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat and managing API keys via the Portal UI or API. - - ### Tips and pitfalls - - * It is possible to delete the last remaining API key. If this happens, a new key can be created via the [API key management page](https://app.codat.io/developers/api-keys) of the Portal. - * It is possible to delete the API key used to authenticate the *Delete API key* request. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DeleteAPIKeyRequest) - request = cast(operations.DeleteAPIKeyRequest, request) - - req = self._build_request( - method="DELETE", - path="/apiKeys/{apiKeyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="delete-api-key", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "application/json"): - return unmarshal_json_response(shared.ErrorMessage, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def delete_api_key_async( - self, - *, - request: Union[ - operations.DeleteAPIKeyRequest, operations.DeleteAPIKeyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ErrorMessage: - r"""Delete API key - - Use the *Delete API keys* endpoint to delete an existing API key, providing its valid `id` as a parameter. Note that this operation is not reversible. - - [API keys](https://docs.codat.io/platform-api#/schemas/apiKeys) are tokens used to control access to the API. Include this token in the `Authorization` header parameter when making API calls, following the word \"Basic\" and a space with your API key. - - You can [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat and managing API keys via the Portal UI or API. - - ### Tips and pitfalls - - * It is possible to delete the last remaining API key. If this happens, a new key can be created via the [API key management page](https://app.codat.io/developers/api-keys) of the Portal. - * It is possible to delete the API key used to authenticate the *Delete API key* request. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DeleteAPIKeyRequest) - request = cast(operations.DeleteAPIKeyRequest, request) - - req = self._build_request_async( - method="DELETE", - path="/apiKeys/{apiKeyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="delete-api-key", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "application/json"): - return unmarshal_json_response(shared.ErrorMessage, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get( - self, - *, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ConnectionManagementAllowedOrigins: - r"""Get CORS settings - - The *Get CORS settings* endpoint returns the allowed origins (i.e. your domains) you want to allow cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)) with Codat. - - Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. - - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - req = self._build_request( - method="GET", - path="/corsSettings", - base_url=base_url, - url_variables=url_variables, - request=None, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-cors-settings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response( - shared.ConnectionManagementAllowedOrigins, http_res - ) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_async( - self, - *, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ConnectionManagementAllowedOrigins: - r"""Get CORS settings - - The *Get CORS settings* endpoint returns the allowed origins (i.e. your domains) you want to allow cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)) with Codat. - - Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. - - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - req = self._build_request_async( - method="GET", - path="/corsSettings", - base_url=base_url, - url_variables=url_variables, - request=None, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-cors-settings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response( - shared.ConnectionManagementAllowedOrigins, http_res - ) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get_profile( - self, - *, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Profile: - r"""Get profile - - Fetch your Codat profile. - - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - req = self._build_request( - method="GET", - path="/profile", - base_url=base_url, - url_variables=url_variables, - request=None, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-profile", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Profile, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_profile_async( - self, - *, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Profile: - r"""Get profile - - Fetch your Codat profile. - - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - req = self._build_request_async( - method="GET", - path="/profile", - base_url=base_url, - url_variables=url_variables, - request=None, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-profile", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Profile, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get_sync_settings( - self, - *, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.SyncSettings: - r"""Get sync settings - - Retrieve the [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings) for your client. This includes how often data types should be queued to be updated, and how much history should be fetched. - - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - req = self._build_request( - method="GET", - path="/profile/syncSettings", - base_url=base_url, - url_variables=url_variables, - request=None, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-profile-syncSettings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.SyncSettings, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_sync_settings_async( - self, - *, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.SyncSettings: - r"""Get sync settings - - Retrieve the [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings) for your client. This includes how often data types should be queued to be updated, and how much history should be fetched. - - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - req = self._build_request_async( - method="GET", - path="/profile/syncSettings", - base_url=base_url, - url_variables=url_variables, - request=None, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-profile-syncSettings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.SyncSettings, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def list_api_keys( - self, - *, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.APIKeys: - r"""List API keys - - Use the *List API keys* endpoint to return a list of all API keys that currently exist for your client. This includes keys created via the Portal UI or the *Create API keys* endpoint. - - [API keys](https://docs.codat.io/platform-api#/schemas/apiKeys) are tokens used to control access to the API. Include this token in the `Authorization` header parameter when making API calls, following the word \"Basic\" and a space with your API key. - - You can [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat and managing API keys via the Portal UI or API. - - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - req = self._build_request( - method="GET", - path="/apiKeys", - base_url=base_url, - url_variables=url_variables, - request=None, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-api-keys", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.APIKeys, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def list_api_keys_async( - self, - *, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.APIKeys: - r"""List API keys - - Use the *List API keys* endpoint to return a list of all API keys that currently exist for your client. This includes keys created via the Portal UI or the *Create API keys* endpoint. - - [API keys](https://docs.codat.io/platform-api#/schemas/apiKeys) are tokens used to control access to the API. Include this token in the `Authorization` header parameter when making API calls, following the word \"Basic\" and a space with your API key. - - You can [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat and managing API keys via the Portal UI or API. - - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - req = self._build_request_async( - method="GET", - path="/apiKeys", - base_url=base_url, - url_variables=url_variables, - request=None, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-api-keys", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.APIKeys, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def set( - self, - *, - request: Optional[ - Union[ - shared.ConnectionManagementAllowedOrigins, - shared.ConnectionManagementAllowedOriginsTypedDict, - ] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ConnectionManagementAllowedOrigins: - r"""Set CORS settings - - The *Set CORS settings* endpoint allows you to register allowed origins (i.e. your domains) for use in cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)). - - Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, Optional[shared.ConnectionManagementAllowedOrigins] - ) - request = cast(Optional[shared.ConnectionManagementAllowedOrigins], request) - - req = self._build_request( - method="POST", - path="/corsSettings", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, - False, - True, - "json", - Optional[shared.ConnectionManagementAllowedOrigins], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="set-cors-settings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response( - shared.ConnectionManagementAllowedOrigins, http_res - ) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def set_async( - self, - *, - request: Optional[ - Union[ - shared.ConnectionManagementAllowedOrigins, - shared.ConnectionManagementAllowedOriginsTypedDict, - ] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.ConnectionManagementAllowedOrigins: - r"""Set CORS settings - - The *Set CORS settings* endpoint allows you to register allowed origins (i.e. your domains) for use in cross-origin resource sharing ([CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)). - - Enabling CORS with Codat is required by our embeddable UIs (such as [Connections SDK](https://docs.codat.io/auth-flow/optimize/connection-management) and [Link SDK](https://docs.codat.io/auth-flow/authorize-embedded-link)) to access Codat's API endpoints. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, Optional[shared.ConnectionManagementAllowedOrigins] - ) - request = cast(Optional[shared.ConnectionManagementAllowedOrigins], request) - - req = self._build_request_async( - method="POST", - path="/corsSettings", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, - False, - True, - "json", - Optional[shared.ConnectionManagementAllowedOrigins], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="set-cors-settings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response( - shared.ConnectionManagementAllowedOrigins, http_res - ) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def update_profile( - self, - *, - request: Optional[Union[shared.Profile, shared.ProfileTypedDict]] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Profile: - r"""Update profile - - Update your Codat profile - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, Optional[shared.Profile]) - request = cast(Optional[shared.Profile], request) - - req = self._build_request( - method="PUT", - path="/profile", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, False, True, "json", Optional[shared.Profile] - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-profile", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Profile, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def update_profile_async( - self, - *, - request: Optional[Union[shared.Profile, shared.ProfileTypedDict]] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Profile: - r"""Update profile - - Update your Codat profile - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, Optional[shared.Profile]) - request = cast(Optional[shared.Profile], request) - - req = self._build_request_async( - method="PUT", - path="/profile", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, False, True, "json", Optional[shared.Profile] - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-profile", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Profile, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def update_sync_settings( - self, - *, - request: Optional[ - Union[ - operations.UpdateProfileSyncSettingsRequestBody, - operations.UpdateProfileSyncSettingsRequestBodyTypedDict, - ] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Update all sync settings - - Update sync settings for all data types. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, Optional[operations.UpdateProfileSyncSettingsRequestBody] - ) - request = cast( - Optional[operations.UpdateProfileSyncSettingsRequestBody], request - ) - - req = self._build_request( - method="POST", - path="/profile/syncSettings", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, - False, - True, - "json", - Optional[operations.UpdateProfileSyncSettingsRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-profile-syncSettings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def update_sync_settings_async( - self, - *, - request: Optional[ - Union[ - operations.UpdateProfileSyncSettingsRequestBody, - operations.UpdateProfileSyncSettingsRequestBodyTypedDict, - ] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Update all sync settings - - Update sync settings for all data types. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, Optional[operations.UpdateProfileSyncSettingsRequestBody] - ) - request = cast( - Optional[operations.UpdateProfileSyncSettingsRequestBody], request - ) - - req = self._build_request_async( - method="POST", - path="/profile/syncSettings", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, - False, - True, - "json", - Optional[operations.UpdateProfileSyncSettingsRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-profile-syncSettings", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_platform.api.settings import Settings diff --git a/platform/src/codat_platform/supplemental_data.py b/platform/src/codat_platform/supplemental_data.py index 29941c3f3..d7b9992b1 100644 --- a/platform/src/codat_platform/supplemental_data.py +++ b/platform/src/codat_platform/supplemental_data.py @@ -1,449 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.supplemental_data — re-export of the supplemental_data method group.""" -from .basesdk import BaseSDK -from codat_platform import utils -from codat_platform._hooks import HookContext -from codat_platform.models import errors, operations, shared -from codat_platform.types import BaseModel, OptionalNullable, UNSET -from codat_platform.utils.unmarshal_json_response import unmarshal_json_response -from typing import Any, Mapping, Optional, Union, cast - - -class SupplementalData(BaseSDK): - r"""Configure and pull additional data you can include in Codat's standard data types.""" - - def configure( - self, - *, - request: Union[ - operations.ConfigureSupplementalDataRequest, - operations.ConfigureSupplementalDataRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Configure - - The *Configure* endpoint allows you to maintain or change configuration required to return supplemental data for each integration and data type combination. - - [Supplemental data](https://docs.codat.io/using-the-api/supplemental-data/overview) is additional data you can include in Codat's standard data types. - - **Integration-specific behavior** - See the *examples* for integration-specific frequently requested properties. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.ConfigureSupplementalDataRequest - ) - request = cast(operations.ConfigureSupplementalDataRequest, request) - - req = self._build_request( - method="PUT", - path="/integrations/{platformKey}/dataTypes/{dataType}/supplementalDataConfig", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.supplemental_data_configuration - if request is not None - else None, - False, - True, - "json", - Optional[shared.SupplementalDataConfiguration], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="configure-supplemental-data", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def configure_async( - self, - *, - request: Union[ - operations.ConfigureSupplementalDataRequest, - operations.ConfigureSupplementalDataRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Configure - - The *Configure* endpoint allows you to maintain or change configuration required to return supplemental data for each integration and data type combination. - - [Supplemental data](https://docs.codat.io/using-the-api/supplemental-data/overview) is additional data you can include in Codat's standard data types. - - **Integration-specific behavior** - See the *examples* for integration-specific frequently requested properties. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.ConfigureSupplementalDataRequest - ) - request = cast(operations.ConfigureSupplementalDataRequest, request) - - req = self._build_request_async( - method="PUT", - path="/integrations/{platformKey}/dataTypes/{dataType}/supplementalDataConfig", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.supplemental_data_configuration - if request is not None - else None, - False, - True, - "json", - Optional[shared.SupplementalDataConfiguration], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="configure-supplemental-data", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get_configuration( - self, - *, - request: Union[ - operations.GetSupplementalDataConfigurationRequest, - operations.GetSupplementalDataConfigurationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.SupplementalDataConfiguration: - r"""Get configuration - - The *Get configuration* endpoint returns supplemental data configuration previously created for each integration and data type combination. - - [Supplemental data](https://docs.codat.io/using-the-api/supplemental-data/overview) is additional data you can include in Codat's standard data types. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetSupplementalDataConfigurationRequest - ) - request = cast(operations.GetSupplementalDataConfigurationRequest, request) - - req = self._build_request( - method="GET", - path="/integrations/{platformKey}/dataTypes/{dataType}/supplementalDataConfig", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-supplemental-data-configuration", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response( - shared.SupplementalDataConfiguration, http_res - ) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_configuration_async( - self, - *, - request: Union[ - operations.GetSupplementalDataConfigurationRequest, - operations.GetSupplementalDataConfigurationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.SupplementalDataConfiguration: - r"""Get configuration - - The *Get configuration* endpoint returns supplemental data configuration previously created for each integration and data type combination. - - [Supplemental data](https://docs.codat.io/using-the-api/supplemental-data/overview) is additional data you can include in Codat's standard data types. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetSupplementalDataConfigurationRequest - ) - request = cast(operations.GetSupplementalDataConfigurationRequest, request) - - req = self._build_request_async( - method="GET", - path="/integrations/{platformKey}/dataTypes/{dataType}/supplementalDataConfig", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-supplemental-data-configuration", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response( - shared.SupplementalDataConfiguration, http_res - ) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_platform.api.supplemental_data import SupplementalData diff --git a/platform/src/codat_platform/types/__init__.py b/platform/src/codat_platform/types/__init__.py index fc76fe0c5..a5e7b8709 100644 --- a/platform/src/codat_platform/types/__init__.py +++ b/platform/src/codat_platform/types/__init__.py @@ -1,21 +1,52 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from .basemodel import ( - BaseModel, - Nullable, - OptionalNullable, - UnrecognizedInt, - UnrecognizedStr, - UNSET, - UNSET_SENTINEL, -) - -__all__ = [ - "BaseModel", - "Nullable", - "OptionalNullable", - "UnrecognizedInt", - "UnrecognizedStr", - "UNSET", - "UNSET_SENTINEL", -] +"""Sentinel / type-alias helpers — matches Speakeasy SDK surface.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Optional, TypeVar, Union +from typing_extensions import Literal, TypeAlias, TypeAliasType + +from pydantic import BaseModel as BaseModel, ConfigDict, model_serializer + +# Speakeasy exposes UnrecognizedInt/UnrecognizedStr as the fallback types for open +# (extensible) enums. POC keeps the plain scalar, so these alias to int/str — a +# consumer annotating with them type-checks and runs identically. +UnrecognizedInt: TypeAlias = int +UnrecognizedStr: TypeAlias = str + +UNSET_SENTINEL = "~?~unset~?~sentinel~?~" + + +class Unset(BaseModel): + """Sentinel distinguishing "not provided" (UNSET) from "explicit None". As a + pydantic model it serializes to UNSET_SENTINEL, so a model serializer can drop + UNSET fields from the wire payload while still emitting explicit nulls.""" + + model_config = ConfigDict(arbitrary_types_allowed=True) + + @model_serializer(mode="plain") + def serialize_model(self): + return UNSET_SENTINEL + + def __bool__(self) -> Literal[False]: + return False + + def __repr__(self) -> str: + return "UNSET" + + +UNSET = Unset() +_Unset = Unset # backwards-compat alias for the class name + +T = TypeVar("T") + +if TYPE_CHECKING: + Nullable: TypeAlias = Union[T, None] + OptionalNullable: TypeAlias = Union[Optional[Nullable[T]], _Unset] +else: + Nullable = TypeAliasType("Nullable", Union[T, None], type_params=(T,)) + OptionalNullable = TypeAliasType( + "OptionalNullable", Union[Optional[T], _Unset], type_params=(T,) + ) + + +__all__ = ["BaseModel", "UNSET", "UNSET_SENTINEL", "Unset", "Nullable", "OptionalNullable", "UnrecognizedInt", "UnrecognizedStr"] diff --git a/platform/src/codat_platform/types/basemodel.py b/platform/src/codat_platform/types/basemodel.py deleted file mode 100644 index a9a640a1a..000000000 --- a/platform/src/codat_platform/types/basemodel.py +++ /dev/null @@ -1,77 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from pydantic import ConfigDict, model_serializer -from pydantic import BaseModel as PydanticBaseModel -from pydantic_core import core_schema -from typing import TYPE_CHECKING, Any, Literal, Optional, TypeVar, Union -from typing_extensions import TypeAliasType, TypeAlias - - -class BaseModel(PydanticBaseModel): - model_config = ConfigDict( - populate_by_name=True, arbitrary_types_allowed=True, protected_namespaces=() - ) - - -class Unset(BaseModel): - @model_serializer(mode="plain") - def serialize_model(self): - return UNSET_SENTINEL - - def __bool__(self) -> Literal[False]: - return False - - -UNSET = Unset() -UNSET_SENTINEL = "~?~unset~?~sentinel~?~" - - -T = TypeVar("T") -if TYPE_CHECKING: - Nullable: TypeAlias = Union[T, None] - OptionalNullable: TypeAlias = Union[Optional[Nullable[T]], Unset] -else: - Nullable = TypeAliasType("Nullable", Union[T, None], type_params=(T,)) - OptionalNullable = TypeAliasType( - "OptionalNullable", Union[Optional[Nullable[T]], Unset], type_params=(T,) - ) - - -class UnrecognizedStr(str): - @classmethod - def __get_pydantic_core_schema__(cls, _source_type: Any, _handler: Any) -> core_schema.CoreSchema: - # Make UnrecognizedStr only work in lax mode, not strict mode - # This makes it a "fallback" option when more specific types (like Literals) don't match - def validate_lax(v: Any) -> 'UnrecognizedStr': - if isinstance(v, cls): - return v - return cls(str(v)) - - # Use lax_or_strict_schema where strict always fails - # This forces Pydantic to prefer other union members in strict mode - # and only fall back to UnrecognizedStr in lax mode - return core_schema.lax_or_strict_schema( - lax_schema=core_schema.chain_schema([ - core_schema.str_schema(), - core_schema.no_info_plain_validator_function(validate_lax) - ]), - strict_schema=core_schema.none_schema(), # Always fails in strict mode - ) - - -class UnrecognizedInt(int): - @classmethod - def __get_pydantic_core_schema__(cls, _source_type: Any, _handler: Any) -> core_schema.CoreSchema: - # Make UnrecognizedInt only work in lax mode, not strict mode - # This makes it a "fallback" option when more specific types (like Literals) don't match - def validate_lax(v: Any) -> 'UnrecognizedInt': - if isinstance(v, cls): - return v - return cls(int(v)) - return core_schema.lax_or_strict_schema( - lax_schema=core_schema.chain_schema([ - core_schema.int_schema(), - core_schema.no_info_plain_validator_function(validate_lax) - ]), - strict_schema=core_schema.none_schema(), # Always fails in strict mode - ) diff --git a/platform/src/codat_platform/utils/__init__.py b/platform/src/codat_platform/utils/__init__.py index 0498cb8da..c821fa4da 100644 --- a/platform/src/codat_platform/utils/__init__.py +++ b/platform/src/codat_platform/utils/__init__.py @@ -1,175 +1,5 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.utils — utility helpers (currently retry config).""" -from typing import Any, TYPE_CHECKING, Callable, TypeVar -import asyncio +from .retries import BackoffStrategy, RetryConfig, Retries -from .dynamic_imports import lazy_getattr, lazy_dir - -_T = TypeVar("_T") - - -async def run_sync_in_thread(func: Callable[..., _T], *args) -> _T: - """Run a synchronous function in a thread pool to avoid blocking the event loop.""" - return await asyncio.to_thread(func, *args) - - -if TYPE_CHECKING: - from .annotations import get_discriminator - from .datetimes import parse_datetime - from .enums import OpenEnumMeta - from .headers import get_headers, get_response_headers - from .metadata import ( - FieldMetadata, - find_metadata, - FormMetadata, - HeaderMetadata, - MultipartFormMetadata, - PathParamMetadata, - QueryParamMetadata, - RequestMetadata, - SecurityMetadata, - ) - from .queryparams import get_query_params - from .retries import BackoffStrategy, Retries, retry, retry_async, RetryConfig - from .requestbodies import serialize_request_body, SerializedRequestBody - from .security import get_security - from .serializers import ( - get_pydantic_model, - marshal_json, - unmarshal, - unmarshal_json, - serialize_decimal, - serialize_float, - serialize_int, - stream_to_text, - stream_to_text_async, - stream_to_bytes, - stream_to_bytes_async, - validate_const, - validate_decimal, - validate_float, - validate_int, - ) - from .url import generate_url, template_url, remove_suffix - from .values import ( - get_global_from_env, - match_content_type, - match_status_codes, - match_response, - cast_partial, - ) - from .logger import Logger, get_body_content, get_default_logger - -__all__ = [ - "BackoffStrategy", - "FieldMetadata", - "find_metadata", - "FormMetadata", - "generate_url", - "get_body_content", - "get_default_logger", - "get_discriminator", - "parse_datetime", - "get_global_from_env", - "get_headers", - "get_pydantic_model", - "get_query_params", - "get_response_headers", - "get_security", - "HeaderMetadata", - "Logger", - "marshal_json", - "match_content_type", - "match_status_codes", - "match_response", - "MultipartFormMetadata", - "OpenEnumMeta", - "PathParamMetadata", - "QueryParamMetadata", - "remove_suffix", - "Retries", - "retry", - "retry_async", - "RetryConfig", - "RequestMetadata", - "SecurityMetadata", - "serialize_decimal", - "serialize_float", - "serialize_int", - "serialize_request_body", - "SerializedRequestBody", - "stream_to_text", - "stream_to_text_async", - "stream_to_bytes", - "stream_to_bytes_async", - "template_url", - "unmarshal", - "unmarshal_json", - "validate_decimal", - "validate_const", - "validate_float", - "validate_int", - "cast_partial", -] - -_dynamic_imports: dict[str, str] = { - "BackoffStrategy": ".retries", - "FieldMetadata": ".metadata", - "find_metadata": ".metadata", - "FormMetadata": ".metadata", - "generate_url": ".url", - "get_body_content": ".logger", - "get_default_logger": ".logger", - "get_discriminator": ".annotations", - "parse_datetime": ".datetimes", - "get_global_from_env": ".values", - "get_headers": ".headers", - "get_pydantic_model": ".serializers", - "get_query_params": ".queryparams", - "get_response_headers": ".headers", - "get_security": ".security", - "HeaderMetadata": ".metadata", - "Logger": ".logger", - "marshal_json": ".serializers", - "match_content_type": ".values", - "match_status_codes": ".values", - "match_response": ".values", - "MultipartFormMetadata": ".metadata", - "OpenEnumMeta": ".enums", - "PathParamMetadata": ".metadata", - "QueryParamMetadata": ".metadata", - "remove_suffix": ".url", - "Retries": ".retries", - "retry": ".retries", - "retry_async": ".retries", - "RetryConfig": ".retries", - "RequestMetadata": ".metadata", - "SecurityMetadata": ".metadata", - "serialize_decimal": ".serializers", - "serialize_float": ".serializers", - "serialize_int": ".serializers", - "serialize_request_body": ".requestbodies", - "SerializedRequestBody": ".requestbodies", - "stream_to_text": ".serializers", - "stream_to_text_async": ".serializers", - "stream_to_bytes": ".serializers", - "stream_to_bytes_async": ".serializers", - "template_url": ".url", - "unmarshal": ".serializers", - "unmarshal_json": ".serializers", - "validate_decimal": ".serializers", - "validate_const": ".serializers", - "validate_float": ".serializers", - "validate_int": ".serializers", - "cast_partial": ".values", -} - - -def __getattr__(attr_name: str) -> Any: - return lazy_getattr( - attr_name, package=__package__, dynamic_imports=_dynamic_imports - ) - - -def __dir__(): - return lazy_dir(dynamic_imports=_dynamic_imports) +__all__ = ["BackoffStrategy", "RetryConfig", "Retries"] diff --git a/platform/src/codat_platform/utils/annotations.py b/platform/src/codat_platform/utils/annotations.py deleted file mode 100644 index 12e0aa4f1..000000000 --- a/platform/src/codat_platform/utils/annotations.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from enum import Enum -from typing import Any, Optional - - -def get_discriminator(model: Any, fieldname: str, key: str) -> str: - """ - Recursively search for the discriminator attribute in a model. - - Args: - model (Any): The model to search within. - fieldname (str): The name of the field to search for. - key (str): The key to search for in dictionaries. - - Returns: - str: The name of the discriminator attribute. - - Raises: - ValueError: If the discriminator attribute is not found. - """ - upper_fieldname = fieldname.upper() - - def get_field_discriminator(field: Any) -> Optional[str]: - """Search for the discriminator attribute in a given field.""" - - if isinstance(field, dict): - if key in field: - return f"{field[key]}" - - if hasattr(field, fieldname): - attr = getattr(field, fieldname) - if isinstance(attr, Enum): - return f"{attr.value}" - return f"{attr}" - - if hasattr(field, upper_fieldname): - attr = getattr(field, upper_fieldname) - if isinstance(attr, Enum): - return f"{attr.value}" - return f"{attr}" - - return None - - def search_nested_discriminator(obj: Any) -> Optional[str]: - """Recursively search for discriminator in nested structures.""" - # First try direct field lookup - discriminator = get_field_discriminator(obj) - if discriminator is not None: - return discriminator - - # If it's a dict, search in nested values - if isinstance(obj, dict): - for value in obj.values(): - if isinstance(value, list): - # Search in list items - for item in value: - nested_discriminator = search_nested_discriminator(item) - if nested_discriminator is not None: - return nested_discriminator - elif isinstance(value, dict): - # Search in nested dict - nested_discriminator = search_nested_discriminator(value) - if nested_discriminator is not None: - return nested_discriminator - - return None - - if isinstance(model, list): - for field in model: - discriminator = search_nested_discriminator(field) - if discriminator is not None: - return discriminator - - discriminator = search_nested_discriminator(model) - if discriminator is not None: - return discriminator - - raise ValueError(f"Could not find discriminator field {fieldname} in {model}") diff --git a/platform/src/codat_platform/utils/datetimes.py b/platform/src/codat_platform/utils/datetimes.py deleted file mode 100644 index a6c52cd61..000000000 --- a/platform/src/codat_platform/utils/datetimes.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from datetime import datetime -import sys - - -def parse_datetime(datetime_string: str) -> datetime: - """ - Convert a RFC 3339 / ISO 8601 formatted string into a datetime object. - Python versions 3.11 and later support parsing RFC 3339 directly with - datetime.fromisoformat(), but for earlier versions, this function - encapsulates the necessary extra logic. - """ - # Python 3.11 and later can parse RFC 3339 directly - if sys.version_info >= (3, 11): - return datetime.fromisoformat(datetime_string) - - # For Python 3.10 and earlier, a common ValueError is trailing 'Z' suffix, - # so fix that upfront. - if datetime_string.endswith("Z"): - datetime_string = datetime_string[:-1] + "+00:00" - - return datetime.fromisoformat(datetime_string) diff --git a/platform/src/codat_platform/utils/dynamic_imports.py b/platform/src/codat_platform/utils/dynamic_imports.py deleted file mode 100644 index 673edf82a..000000000 --- a/platform/src/codat_platform/utils/dynamic_imports.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from importlib import import_module -import builtins -import sys - - -def dynamic_import(package, modname, retries=3): - """Import a module relative to package, retrying on KeyError from half-initialized modules.""" - for attempt in range(retries): - try: - return import_module(modname, package) - except KeyError: - sys.modules.pop(modname, None) - if attempt == retries - 1: - break - raise KeyError(f"Failed to import module '{modname}' after {retries} attempts") - - -def lazy_getattr(attr_name, *, package, dynamic_imports, sub_packages=None): - """Module-level __getattr__ that lazily loads from a dynamic_imports mapping. - - Args: - attr_name: The attribute being looked up. - package: The caller's __package__ (for relative imports). - dynamic_imports: Dict mapping attribute names to relative module paths. - sub_packages: Optional list of subpackage names to lazy-load. - """ - module_name = dynamic_imports.get(attr_name) - if module_name is not None: - try: - module = dynamic_import(package, module_name) - return getattr(module, attr_name) - except ImportError as e: - raise ImportError( - f"Failed to import {attr_name} from {module_name}: {e}" - ) from e - except AttributeError as e: - raise AttributeError( - f"Failed to get {attr_name} from {module_name}: {e}" - ) from e - - if sub_packages and attr_name in sub_packages: - return import_module(f".{attr_name}", package) - - raise AttributeError(f"module '{package}' has no attribute '{attr_name}'") - - -def lazy_dir(*, dynamic_imports, sub_packages=None): - """Module-level __dir__ that lists lazily-loadable attributes.""" - lazy_attrs = builtins.list(dynamic_imports.keys()) - if sub_packages: - lazy_attrs.extend(sub_packages) - return builtins.sorted(lazy_attrs) diff --git a/platform/src/codat_platform/utils/enums.py b/platform/src/codat_platform/utils/enums.py deleted file mode 100644 index 3324e1bc2..000000000 --- a/platform/src/codat_platform/utils/enums.py +++ /dev/null @@ -1,134 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -import enum -import sys -from typing import Any - -from pydantic_core import core_schema - - -class OpenEnumMeta(enum.EnumMeta): - # The __call__ method `boundary` kwarg was added in 3.11 and must be present - # for pyright. Refer also: https://github.com/pylint-dev/pylint/issues/9622 - # pylint: disable=unexpected-keyword-arg - # The __call__ method `values` varg must be named for pyright. - # pylint: disable=keyword-arg-before-vararg - - if sys.version_info >= (3, 11): - def __call__( - cls, value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None - ): - # The `type` kwarg also happens to be a built-in that pylint flags as - # redeclared. Safe to ignore this lint rule with this scope. - # pylint: disable=redefined-builtin - - if names is not None: - return super().__call__( - value, - names=names, - *values, - module=module, - qualname=qualname, - type=type, - start=start, - boundary=boundary, - ) - - try: - return super().__call__( - value, - names=names, # pyright: ignore[reportArgumentType] - *values, - module=module, - qualname=qualname, - type=type, - start=start, - boundary=boundary, - ) - except ValueError: - return value - else: - def __call__( - cls, value, names=None, *, module=None, qualname=None, type=None, start=1 - ): - # The `type` kwarg also happens to be a built-in that pylint flags as - # redeclared. Safe to ignore this lint rule with this scope. - # pylint: disable=redefined-builtin - - if names is not None: - return super().__call__( - value, - names=names, - module=module, - qualname=qualname, - type=type, - start=start, - ) - - try: - return super().__call__( - value, - names=names, # pyright: ignore[reportArgumentType] - module=module, - qualname=qualname, - type=type, - start=start, - ) - except ValueError: - return value - - def __new__(mcs, name, bases, namespace, **kwargs): - cls = super().__new__(mcs, name, bases, namespace, **kwargs) - - # Add __get_pydantic_core_schema__ to make open enums work correctly - # in union discrimination. In strict mode (used by Pydantic for unions), - # only known enum values match. In lax mode, unknown values are accepted. - def __get_pydantic_core_schema__( - cls_inner: Any, _source_type: Any, _handler: Any - ) -> core_schema.CoreSchema: - # Create a validator that only accepts known enum values (for strict mode) - def validate_strict(v: Any) -> Any: - if isinstance(v, cls_inner): - return v - # Use the parent EnumMeta's __call__ which raises ValueError for unknown values - return enum.EnumMeta.__call__(cls_inner, v) - - # Create a lax validator that accepts unknown values - def validate_lax(v: Any) -> Any: - if isinstance(v, cls_inner): - return v - try: - return enum.EnumMeta.__call__(cls_inner, v) - except ValueError: - # Return the raw value for unknown enum values - return v - - # Determine the base type schema (str or int) - is_int_enum = False - for base in cls_inner.__mro__: - if base is int: - is_int_enum = True - break - if base is str: - break - - base_schema = ( - core_schema.int_schema() - if is_int_enum - else core_schema.str_schema() - ) - - # Use lax_or_strict_schema: - # - strict mode: only known enum values match (raises ValueError for unknown) - # - lax mode: accept any value, return enum member or raw value - return core_schema.lax_or_strict_schema( - lax_schema=core_schema.chain_schema( - [base_schema, core_schema.no_info_plain_validator_function(validate_lax)] - ), - strict_schema=core_schema.chain_schema( - [base_schema, core_schema.no_info_plain_validator_function(validate_strict)] - ), - ) - - setattr(cls, "__get_pydantic_core_schema__", classmethod(__get_pydantic_core_schema__)) - return cls diff --git a/platform/src/codat_platform/utils/eventstreaming.py b/platform/src/codat_platform/utils/eventstreaming.py deleted file mode 100644 index 3bdcd6d3d..000000000 --- a/platform/src/codat_platform/utils/eventstreaming.py +++ /dev/null @@ -1,309 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -import re -import json -from dataclasses import dataclass, asdict -from typing import ( - Any, - Callable, - Generic, - TypeVar, - Optional, - Generator, - AsyncGenerator, - Tuple, -) -import httpx - -T = TypeVar("T") - - -class EventStream(Generic[T]): - # Holds a reference to the SDK client to avoid it being garbage collected - # and cause termination of the underlying httpx client. - client_ref: Optional[object] - response: httpx.Response - generator: Generator[T, None, None] - _closed: bool - - def __init__( - self, - response: httpx.Response, - decoder: Callable[[str], T], - sentinel: Optional[str] = None, - client_ref: Optional[object] = None, - data_required: bool = True, - ): - self.response = response - self.generator = stream_events( - response, decoder, sentinel, data_required=data_required - ) - self.client_ref = client_ref - self._closed = False - - def __iter__(self): - return self - - def __next__(self): - if self._closed: - raise StopIteration - return next(self.generator) - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - self._closed = True - self.response.close() - - -class EventStreamAsync(Generic[T]): - # Holds a reference to the SDK client to avoid it being garbage collected - # and cause termination of the underlying httpx client. - client_ref: Optional[object] - response: httpx.Response - generator: AsyncGenerator[T, None] - _closed: bool - - def __init__( - self, - response: httpx.Response, - decoder: Callable[[str], T], - sentinel: Optional[str] = None, - client_ref: Optional[object] = None, - data_required: bool = True, - ): - self.response = response - self.generator = stream_events_async( - response, decoder, sentinel, data_required=data_required - ) - self.client_ref = client_ref - self._closed = False - - def __aiter__(self): - return self - - async def __anext__(self): - if self._closed: - raise StopAsyncIteration - return await self.generator.__anext__() - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc_val, exc_tb): - self._closed = True - await self.response.aclose() - - -@dataclass -class ServerEvent: - id: Optional[str] = None - event: Optional[str] = None - data: Any = None - retry: Optional[int] = None - - -MESSAGE_BOUNDARIES = [ - b"\r\n\r\n", - b"\r\n\r", - b"\r\n\n", - b"\r\r\n", - b"\n\r\n", - b"\r\r", - b"\n\r", - b"\n\n", -] - -UTF8_BOM = b"\xef\xbb\xbf" - - -async def stream_events_async( - response: httpx.Response, - decoder: Callable[[str], T], - sentinel: Optional[str] = None, - data_required: bool = True, -) -> AsyncGenerator[T, None]: - buffer = bytearray() - position = 0 - event_id: Optional[str] = None - async for chunk in response.aiter_bytes(): - if len(buffer) == 0 and chunk.startswith(UTF8_BOM): - chunk = chunk[len(UTF8_BOM) :] - buffer += chunk - for i in range(position, len(buffer)): - char = buffer[i : i + 1] - seq: Optional[bytes] = None - if char in [b"\r", b"\n"]: - for boundary in MESSAGE_BOUNDARIES: - seq = _peek_sequence(i, buffer, boundary) - if seq is not None: - break - if seq is None: - continue - - block = buffer[position:i] - position = i + len(seq) - event, discard, event_id = _parse_event( - raw=block, - decoder=decoder, - sentinel=sentinel, - event_id=event_id, - data_required=data_required, - ) - if event is not None: - yield event - if discard: - await response.aclose() - return - - if position > 0: - buffer = buffer[position:] - position = 0 - - event, discard, _ = _parse_event( - raw=buffer, - decoder=decoder, - sentinel=sentinel, - event_id=event_id, - data_required=data_required, - ) - if event is not None: - yield event - - -def stream_events( - response: httpx.Response, - decoder: Callable[[str], T], - sentinel: Optional[str] = None, - data_required: bool = True, -) -> Generator[T, None, None]: - buffer = bytearray() - position = 0 - event_id: Optional[str] = None - for chunk in response.iter_bytes(): - if len(buffer) == 0 and chunk.startswith(UTF8_BOM): - chunk = chunk[len(UTF8_BOM) :] - buffer += chunk - for i in range(position, len(buffer)): - char = buffer[i : i + 1] - seq: Optional[bytes] = None - if char in [b"\r", b"\n"]: - for boundary in MESSAGE_BOUNDARIES: - seq = _peek_sequence(i, buffer, boundary) - if seq is not None: - break - if seq is None: - continue - - block = buffer[position:i] - position = i + len(seq) - event, discard, event_id = _parse_event( - raw=block, - decoder=decoder, - sentinel=sentinel, - event_id=event_id, - data_required=data_required, - ) - if event is not None: - yield event - if discard: - response.close() - return - - if position > 0: - buffer = buffer[position:] - position = 0 - - event, discard, _ = _parse_event( - raw=buffer, - decoder=decoder, - sentinel=sentinel, - event_id=event_id, - data_required=data_required, - ) - if event is not None: - yield event - - -def _parse_event( - *, - raw: bytearray, - decoder: Callable[[str], T], - sentinel: Optional[str] = None, - event_id: Optional[str] = None, - data_required: bool = True, -) -> Tuple[Optional[T], bool, Optional[str]]: - block = raw.decode() - lines = re.split(r"\r?\n|\r", block) - publish = False - event = ServerEvent() - data = "" - for line in lines: - if not line: - continue - - delim = line.find(":") - if delim == 0: - continue - - field = line - value = "" - if delim > 0: - field = line[0:delim] - value = line[delim + 1 :] if delim < len(line) - 1 else "" - if len(value) and value[0] == " ": - value = value[1:] - - if field == "event": - event.event = value - publish = True - elif field == "data": - data += value + "\n" - publish = True - elif field == "id": - publish = True - if "\x00" not in value: - event_id = value - elif field == "retry": - if value.isdigit(): - event.retry = int(value) - publish = True - - event.id = event_id - - if sentinel and data == f"{sentinel}\n": - return None, True, event_id - - # Skip data-less events when data is required - if not data and publish and data_required: - return None, False, event_id - - if data: - data = data[:-1] - try: - event.data = json.loads(data) - except json.JSONDecodeError: - event.data = data - - out = None - if publish: - out_dict = { - k: v - for k, v in asdict(event).items() - if v is not None or (k == "data" and data) - } - out = decoder(json.dumps(out_dict)) - - return out, False, event_id - - -def _peek_sequence(position: int, buffer: bytearray, sequence: bytes): - if len(sequence) > (len(buffer) - position): - return None - - for i, seq in enumerate(sequence): - if buffer[position + i] != seq: - return None - - return sequence diff --git a/platform/src/codat_platform/utils/forms.py b/platform/src/codat_platform/utils/forms.py deleted file mode 100644 index f961e76be..000000000 --- a/platform/src/codat_platform/utils/forms.py +++ /dev/null @@ -1,234 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from typing import ( - Any, - Dict, - get_type_hints, - List, - Tuple, -) -from pydantic import BaseModel -from pydantic.fields import FieldInfo - -from .serializers import marshal_json - -from .metadata import ( - FormMetadata, - MultipartFormMetadata, - find_field_metadata, -) -from .values import _is_set, _val_to_string - - -def _populate_form( - field_name: str, - explode: bool, - obj: Any, - delimiter: str, - form: Dict[str, List[str]], -): - if not _is_set(obj): - return form - - if isinstance(obj, BaseModel): - items = [] - - obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields - for name in obj_fields: - obj_field = obj_fields[name] - obj_field_name = obj_field.alias if obj_field.alias is not None else name - if obj_field_name == "": - continue - - val = getattr(obj, name) - if not _is_set(val): - continue - - if explode: - form[obj_field_name] = [_val_to_string(val)] - else: - items.append(f"{obj_field_name}{delimiter}{_val_to_string(val)}") - - if len(items) > 0: - form[field_name] = [delimiter.join(items)] - elif isinstance(obj, Dict): - items = [] - for key, value in obj.items(): - if not _is_set(value): - continue - - if explode: - form[key] = [_val_to_string(value)] - else: - items.append(f"{key}{delimiter}{_val_to_string(value)}") - - if len(items) > 0: - form[field_name] = [delimiter.join(items)] - elif isinstance(obj, List): - items = [] - - for value in obj: - if not _is_set(value): - continue - - if explode: - if not field_name in form: - form[field_name] = [] - form[field_name].append(_val_to_string(value)) - else: - items.append(_val_to_string(value)) - - if len(items) > 0: - form[field_name] = [delimiter.join([str(item) for item in items])] - else: - form[field_name] = [_val_to_string(obj)] - - return form - - -def _extract_file_properties(file_obj: Any) -> Tuple[str, Any, Any]: - """Extract file name, content, and content type from a file object.""" - file_fields: Dict[str, FieldInfo] = file_obj.__class__.model_fields - - file_name = "" - content = None - content_type = None - - for file_field_name in file_fields: - file_field = file_fields[file_field_name] - - file_metadata = find_field_metadata(file_field, MultipartFormMetadata) - if file_metadata is None: - continue - - if file_metadata.content: - content = getattr(file_obj, file_field_name, None) - elif file_field_name == "content_type": - content_type = getattr(file_obj, file_field_name, None) - else: - file_name = getattr(file_obj, file_field_name) - - if file_name == "" or content is None: - raise ValueError("invalid multipart/form-data file") - - return file_name, content, content_type - - -def serialize_multipart_form( - media_type: str, request: Any -) -> Tuple[str, Dict[str, Any], List[Tuple[str, Any]]]: - form: Dict[str, Any] = {} - files: List[Tuple[str, Any]] = [] - - if not isinstance(request, BaseModel): - raise TypeError("invalid request body type") - - request_fields: Dict[str, FieldInfo] = request.__class__.model_fields - request_field_types = get_type_hints(request.__class__) - - for name in request_fields: - field = request_fields[name] - - val = getattr(request, name) - if not _is_set(val): - continue - - field_metadata = find_field_metadata(field, MultipartFormMetadata) - if not field_metadata: - continue - - f_name = field.alias if field.alias else name - - if field_metadata.file: - if isinstance(val, List): - # Handle array of files - array_field_name = f_name + "[]" - for file_obj in val: - if not _is_set(file_obj): - continue - - file_name, content, content_type = _extract_file_properties( - file_obj - ) - - if content_type is not None: - files.append( - (array_field_name, (file_name, content, content_type)) - ) - else: - files.append((array_field_name, (file_name, content))) - else: - # Handle single file - file_name, content, content_type = _extract_file_properties(val) - - if content_type is not None: - files.append((f_name, (file_name, content, content_type))) - else: - files.append((f_name, (file_name, content))) - elif field_metadata.json: - files.append( - ( - f_name, - ( - None, - marshal_json(val, request_field_types[name]), - "application/json", - ), - ) - ) - else: - if isinstance(val, List): - values = [] - - for value in val: - if not _is_set(value): - continue - values.append(_val_to_string(value)) - - array_field_name = f_name + "[]" - form[array_field_name] = values - else: - form[f_name] = _val_to_string(val) - return media_type, form, files - - -def serialize_form_data(data: Any) -> Dict[str, Any]: - form: Dict[str, List[str]] = {} - - if isinstance(data, BaseModel): - data_fields: Dict[str, FieldInfo] = data.__class__.model_fields - data_field_types = get_type_hints(data.__class__) - for name in data_fields: - field = data_fields[name] - - val = getattr(data, name) - if not _is_set(val): - continue - - metadata = find_field_metadata(field, FormMetadata) - if metadata is None: - continue - - f_name = field.alias if field.alias is not None else name - - if metadata.json: - form[f_name] = [marshal_json(val, data_field_types[name])] - else: - if metadata.style == "form": - _populate_form( - f_name, - metadata.explode, - val, - ",", - form, - ) - else: - raise ValueError(f"Invalid form style for field {name}") - elif isinstance(data, Dict): - for key, value in data.items(): - if _is_set(value): - form[key] = [_val_to_string(value)] - else: - raise TypeError(f"Invalid request body type {type(data)} for form data") - - return form diff --git a/platform/src/codat_platform/utils/headers.py b/platform/src/codat_platform/utils/headers.py deleted file mode 100644 index 37864cbbb..000000000 --- a/platform/src/codat_platform/utils/headers.py +++ /dev/null @@ -1,136 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from typing import ( - Any, - Dict, - List, - Optional, -) -from httpx import Headers -from pydantic import BaseModel -from pydantic.fields import FieldInfo - -from .metadata import ( - HeaderMetadata, - find_field_metadata, -) - -from .values import _is_set, _populate_from_globals, _val_to_string - - -def get_headers(headers_params: Any, gbls: Optional[Any] = None) -> Dict[str, str]: - headers: Dict[str, str] = {} - - globals_already_populated = [] - if _is_set(headers_params): - globals_already_populated = _populate_headers(headers_params, gbls, headers, []) - if _is_set(gbls): - _populate_headers(gbls, None, headers, globals_already_populated) - - return headers - - -def _populate_headers( - headers_params: Any, - gbls: Any, - header_values: Dict[str, str], - skip_fields: List[str], -) -> List[str]: - globals_already_populated: List[str] = [] - - if not isinstance(headers_params, BaseModel): - return globals_already_populated - - param_fields: Dict[str, FieldInfo] = headers_params.__class__.model_fields - for name in param_fields: - if name in skip_fields: - continue - - field = param_fields[name] - f_name = field.alias if field.alias is not None else name - - metadata = find_field_metadata(field, HeaderMetadata) - if metadata is None: - continue - - value, global_found = _populate_from_globals( - name, getattr(headers_params, name), HeaderMetadata, gbls - ) - if global_found: - globals_already_populated.append(name) - value = _serialize_header(metadata.explode, value) - - if value != "": - header_values[f_name] = value - - return globals_already_populated - - -def _serialize_header(explode: bool, obj: Any) -> str: - if not _is_set(obj): - return "" - - if isinstance(obj, BaseModel): - items = [] - obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields - for name in obj_fields: - obj_field = obj_fields[name] - obj_param_metadata = find_field_metadata(obj_field, HeaderMetadata) - - if not obj_param_metadata: - continue - - f_name = obj_field.alias if obj_field.alias is not None else name - - val = getattr(obj, name) - if not _is_set(val): - continue - - if explode: - items.append(f"{f_name}={_val_to_string(val)}") - else: - items.append(f_name) - items.append(_val_to_string(val)) - - if len(items) > 0: - return ",".join(items) - elif isinstance(obj, Dict): - items = [] - - for key, value in obj.items(): - if not _is_set(value): - continue - - if explode: - items.append(f"{key}={_val_to_string(value)}") - else: - items.append(key) - items.append(_val_to_string(value)) - - if len(items) > 0: - return ",".join([str(item) for item in items]) - elif isinstance(obj, List): - items = [] - - for value in obj: - if not _is_set(value): - continue - - items.append(_val_to_string(value)) - - if len(items) > 0: - return ",".join(items) - elif _is_set(obj): - return f"{_val_to_string(obj)}" - - return "" - - -def get_response_headers(headers: Headers) -> Dict[str, List[str]]: - res: Dict[str, List[str]] = {} - for k, v in headers.items(): - if not k in res: - res[k] = [] - - res[k].append(v) - return res diff --git a/platform/src/codat_platform/utils/logger.py b/platform/src/codat_platform/utils/logger.py deleted file mode 100644 index b661aff65..000000000 --- a/platform/src/codat_platform/utils/logger.py +++ /dev/null @@ -1,22 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -import httpx -from typing import Any, Protocol - - -class Logger(Protocol): - def debug(self, msg: str, *args: Any, **kwargs: Any) -> None: - pass - - -class NoOpLogger: - def debug(self, msg: str, *args: Any, **kwargs: Any) -> None: - pass - - -def get_body_content(req: httpx.Request) -> str: - return "" if not hasattr(req, "_content") else str(req.content) - - -def get_default_logger() -> Logger: - return NoOpLogger() diff --git a/platform/src/codat_platform/utils/metadata.py b/platform/src/codat_platform/utils/metadata.py deleted file mode 100644 index 5abddd588..000000000 --- a/platform/src/codat_platform/utils/metadata.py +++ /dev/null @@ -1,119 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from typing import Optional, Type, TypeVar, Union -from dataclasses import dataclass -from pydantic.fields import FieldInfo - - -T = TypeVar("T") - - -@dataclass -class SecurityMetadata: - option: bool = False - scheme: bool = False - scheme_type: Optional[str] = None - sub_type: Optional[str] = None - field_name: Optional[str] = None - composite: bool = False - - def get_field_name(self, default: str) -> str: - return self.field_name or default - - -@dataclass -class ParamMetadata: - serialization: Optional[str] = None - style: str = "simple" - explode: bool = False - - -@dataclass -class PathParamMetadata(ParamMetadata): - pass - - -@dataclass -class QueryParamMetadata(ParamMetadata): - style: str = "form" - explode: bool = True - - -@dataclass -class HeaderMetadata(ParamMetadata): - pass - - -@dataclass -class RequestMetadata: - media_type: str = "application/octet-stream" - - -@dataclass -class MultipartFormMetadata: - file: bool = False - content: bool = False - json: bool = False - - -@dataclass -class FormMetadata: - json: bool = False - style: str = "form" - explode: bool = True - - -class FieldMetadata: - security: Optional[SecurityMetadata] = None - path: Optional[PathParamMetadata] = None - query: Optional[QueryParamMetadata] = None - header: Optional[HeaderMetadata] = None - request: Optional[RequestMetadata] = None - form: Optional[FormMetadata] = None - multipart: Optional[MultipartFormMetadata] = None - - def __init__( - self, - security: Optional[SecurityMetadata] = None, - path: Optional[Union[PathParamMetadata, bool]] = None, - query: Optional[Union[QueryParamMetadata, bool]] = None, - header: Optional[Union[HeaderMetadata, bool]] = None, - request: Optional[Union[RequestMetadata, bool]] = None, - form: Optional[Union[FormMetadata, bool]] = None, - multipart: Optional[Union[MultipartFormMetadata, bool]] = None, - ): - self.security = security - self.path = PathParamMetadata() if isinstance(path, bool) else path - self.query = QueryParamMetadata() if isinstance(query, bool) else query - self.header = HeaderMetadata() if isinstance(header, bool) else header - self.request = RequestMetadata() if isinstance(request, bool) else request - self.form = FormMetadata() if isinstance(form, bool) else form - self.multipart = ( - MultipartFormMetadata() if isinstance(multipart, bool) else multipart - ) - - -def find_field_metadata(field_info: FieldInfo, metadata_type: Type[T]) -> Optional[T]: - metadata = find_metadata(field_info, FieldMetadata) - if not metadata: - return None - - fields = metadata.__dict__ - - for field in fields: - if isinstance(fields[field], metadata_type): - return fields[field] - - return None - - -def find_metadata(field_info: FieldInfo, metadata_type: Type[T]) -> Optional[T]: - metadata = field_info.metadata - if not metadata: - return None - - for md in metadata: - if isinstance(md, metadata_type): - return md - - return None diff --git a/platform/src/codat_platform/utils/queryparams.py b/platform/src/codat_platform/utils/queryparams.py deleted file mode 100644 index c04e0db82..000000000 --- a/platform/src/codat_platform/utils/queryparams.py +++ /dev/null @@ -1,217 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from typing import ( - Any, - Dict, - get_type_hints, - List, - Optional, -) - -from pydantic import BaseModel -from pydantic.fields import FieldInfo - -from .metadata import ( - QueryParamMetadata, - find_field_metadata, -) -from .values import ( - _get_serialized_params, - _is_set, - _populate_from_globals, - _val_to_string, -) -from .forms import _populate_form - - -def get_query_params( - query_params: Any, - gbls: Optional[Any] = None, - allow_empty_value: Optional[List[str]] = None, -) -> Dict[str, List[str]]: - params: Dict[str, List[str]] = {} - - globals_already_populated = _populate_query_params(query_params, gbls, params, [], allow_empty_value) - if _is_set(gbls): - _populate_query_params(gbls, None, params, globals_already_populated, allow_empty_value) - - return params - - -def _populate_query_params( - query_params: Any, - gbls: Any, - query_param_values: Dict[str, List[str]], - skip_fields: List[str], - allow_empty_value: Optional[List[str]] = None, -) -> List[str]: - globals_already_populated: List[str] = [] - - if not isinstance(query_params, BaseModel): - return globals_already_populated - - param_fields: Dict[str, FieldInfo] = query_params.__class__.model_fields - param_field_types = get_type_hints(query_params.__class__) - for name in param_fields: - if name in skip_fields: - continue - - field = param_fields[name] - - metadata = find_field_metadata(field, QueryParamMetadata) - if not metadata: - continue - - value = getattr(query_params, name) if _is_set(query_params) else None - - value, global_found = _populate_from_globals( - name, value, QueryParamMetadata, gbls - ) - if global_found: - globals_already_populated.append(name) - - f_name = field.alias if field.alias is not None else name - - allow_empty_set = set(allow_empty_value or []) - should_include_empty = f_name in allow_empty_set and ( - value is None or value == [] or value == "" - ) - - if should_include_empty: - query_param_values[f_name] = [""] - continue - - serialization = metadata.serialization - if serialization is not None: - serialized_parms = _get_serialized_params( - metadata, f_name, value, param_field_types[name] - ) - for key, value in serialized_parms.items(): - if key in query_param_values: - query_param_values[key].extend(value) - else: - query_param_values[key] = [value] - else: - style = metadata.style - if style == "deepObject": - _populate_deep_object_query_params(f_name, value, query_param_values) - elif style == "form": - _populate_delimited_query_params( - metadata, f_name, value, ",", query_param_values - ) - elif style == "pipeDelimited": - _populate_delimited_query_params( - metadata, f_name, value, "|", query_param_values - ) - else: - raise NotImplementedError( - f"query param style {style} not yet supported" - ) - - return globals_already_populated - - -def _populate_deep_object_query_params( - field_name: str, - obj: Any, - params: Dict[str, List[str]], -): - if not _is_set(obj): - return - - if isinstance(obj, BaseModel): - _populate_deep_object_query_params_basemodel(field_name, obj, params) - elif isinstance(obj, Dict): - _populate_deep_object_query_params_dict(field_name, obj, params) - - -def _populate_deep_object_query_params_basemodel( - prior_params_key: str, - obj: Any, - params: Dict[str, List[str]], -): - if not _is_set(obj) or not isinstance(obj, BaseModel): - return - - obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields - for name in obj_fields: - obj_field = obj_fields[name] - - f_name = obj_field.alias if obj_field.alias is not None else name - - params_key = f"{prior_params_key}[{f_name}]" - - obj_param_metadata = find_field_metadata(obj_field, QueryParamMetadata) - if not _is_set(obj_param_metadata): - continue - - obj_val = getattr(obj, name) - if not _is_set(obj_val): - continue - - if isinstance(obj_val, BaseModel): - _populate_deep_object_query_params_basemodel(params_key, obj_val, params) - elif isinstance(obj_val, Dict): - _populate_deep_object_query_params_dict(params_key, obj_val, params) - elif isinstance(obj_val, List): - _populate_deep_object_query_params_list(params_key, obj_val, params) - else: - params[params_key] = [_val_to_string(obj_val)] - - -def _populate_deep_object_query_params_dict( - prior_params_key: str, - value: Dict, - params: Dict[str, List[str]], -): - if not _is_set(value): - return - - for key, val in value.items(): - if not _is_set(val): - continue - - params_key = f"{prior_params_key}[{key}]" - - if isinstance(val, BaseModel): - _populate_deep_object_query_params_basemodel(params_key, val, params) - elif isinstance(val, Dict): - _populate_deep_object_query_params_dict(params_key, val, params) - elif isinstance(val, List): - _populate_deep_object_query_params_list(params_key, val, params) - else: - params[params_key] = [_val_to_string(val)] - - -def _populate_deep_object_query_params_list( - params_key: str, - value: List, - params: Dict[str, List[str]], -): - if not _is_set(value): - return - - for val in value: - if not _is_set(val): - continue - - if params.get(params_key) is None: - params[params_key] = [] - - params[params_key].append(_val_to_string(val)) - - -def _populate_delimited_query_params( - metadata: QueryParamMetadata, - field_name: str, - obj: Any, - delimiter: str, - query_param_values: Dict[str, List[str]], -): - _populate_form( - field_name, - metadata.explode, - obj, - delimiter, - query_param_values, - ) diff --git a/platform/src/codat_platform/utils/requestbodies.py b/platform/src/codat_platform/utils/requestbodies.py deleted file mode 100644 index 1de32b6d2..000000000 --- a/platform/src/codat_platform/utils/requestbodies.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -import io -from dataclasses import dataclass -import re -from typing import ( - Any, - Optional, -) - -from .forms import serialize_form_data, serialize_multipart_form - -from .serializers import marshal_json - -SERIALIZATION_METHOD_TO_CONTENT_TYPE = { - "json": "application/json", - "form": "application/x-www-form-urlencoded", - "multipart": "multipart/form-data", - "raw": "application/octet-stream", - "string": "text/plain", -} - - -@dataclass -class SerializedRequestBody: - media_type: Optional[str] = None - content: Optional[Any] = None - data: Optional[Any] = None - files: Optional[Any] = None - - -def serialize_request_body( - request_body: Any, - nullable: bool, - optional: bool, - serialization_method: str, - request_body_type, -) -> Optional[SerializedRequestBody]: - if request_body is None: - if not nullable and optional: - return None - - media_type = SERIALIZATION_METHOD_TO_CONTENT_TYPE[serialization_method] - - serialized_request_body = SerializedRequestBody(media_type) - - if re.match(r"^(application|text)\/([^+]+\+)*json.*", media_type) is not None: - serialized_request_body.content = marshal_json(request_body, request_body_type) - elif re.match(r"^multipart\/.*", media_type) is not None: - ( - serialized_request_body.media_type, - serialized_request_body.data, - serialized_request_body.files, - ) = serialize_multipart_form(media_type, request_body) - elif re.match(r"^application\/x-www-form-urlencoded.*", media_type) is not None: - serialized_request_body.data = serialize_form_data(request_body) - elif isinstance(request_body, (bytes, bytearray, io.BytesIO, io.BufferedReader)): - serialized_request_body.content = request_body - elif isinstance(request_body, str): - serialized_request_body.content = request_body - else: - raise TypeError( - f"invalid request body type {type(request_body)} for mediaType {media_type}" - ) - - return serialized_request_body diff --git a/platform/src/codat_platform/utils/retries.py b/platform/src/codat_platform/utils/retries.py index af07d4e94..28b22e85e 100644 --- a/platform/src/codat_platform/utils/retries.py +++ b/platform/src/codat_platform/utils/retries.py @@ -1,13 +1,13 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Retry configuration matching Speakeasy SDK surface, with runtime backoff loop.""" + +from __future__ import annotations -import asyncio import random import time +import urllib3 from datetime import datetime from email.utils import parsedate_to_datetime -from typing import List, Optional - -import httpx +from typing import Any, Callable, Iterable, List, Optional, Set class BackoffStrategy: @@ -18,10 +18,10 @@ class BackoffStrategy: def __init__( self, - initial_interval: int, - max_interval: int, - exponent: float, - max_elapsed_time: int, + initial_interval: int = 500, + max_interval: int = 60000, + exponent: float = 1.5, + max_elapsed_time: int = 3600000, ): self.initial_interval = initial_interval self.max_interval = max_interval @@ -35,10 +35,13 @@ class RetryConfig: retry_connection_errors: bool def __init__( - self, strategy: str, backoff: BackoffStrategy, retry_connection_errors: bool + self, + strategy: str = "backoff", + backoff: Optional[BackoffStrategy] = None, + retry_connection_errors: bool = True, ): self.strategy = strategy - self.backoff = backoff + self.backoff = backoff if backoff is not None else BackoffStrategy() self.retry_connection_errors = retry_connection_errors @@ -51,221 +54,119 @@ def __init__(self, config: RetryConfig, status_codes: List[str]): self.status_codes = status_codes -class TemporaryError(Exception): - response: httpx.Response - retry_after: Optional[int] - - def __init__(self, response: httpx.Response): - self.response = response - self.retry_after = _parse_retry_after_header(response) - - -class PermanentError(Exception): - inner: Exception - - def __init__(self, inner: Exception): - self.inner = inner - - -def _parse_retry_after_header(response: httpx.Response) -> Optional[int]: - """Parse Retry-After header from response. - - Returns: - Retry interval in milliseconds, or None if header is missing or invalid. - """ - retry_after_header = response.headers.get("retry-after") - if not retry_after_header: +# Default retryable status codes from the OAS (x-speakeasy-retries.statusCodes). +# Entries may be ints or strings like "5XX" denoting wildcards across a hundred-block. +DEFAULT_RETRY_STATUS_CODES: List[Any] = [408, 429, '5XX'] + + +def _matches_status(code: int, retry_codes: Iterable[Any]) -> bool: + for entry in retry_codes: + if isinstance(entry, int) and entry == code: + return True + if isinstance(entry, str): + entry_u = entry.upper() + if entry_u.endswith("XX") and len(entry_u) == 3 and entry_u[0].isdigit(): + if (code // 100) == int(entry_u[0]): + return True + else: + try: + if int(entry_u) == code: + return True + except ValueError: + pass + return False + + +def _retry_after_ms(exc: Any) -> Optional[int]: + """Milliseconds to wait from a response's Retry-After header, or None if absent. + Accepts an integer number of seconds or an HTTP date, matching Speakeasy and the + TypeScript runtime. A past date clamps to 0.""" + headers = getattr(exc, "headers", None) + if not headers: return None - - try: - seconds = float(retry_after_header) - return round(seconds * 1000) - except ValueError: - pass - + getter = getattr(headers, "get", None) + if getter is None: + return None + value = getter("Retry-After") + if value is None: + value = getter("retry-after") + if value is None: + return None + text = str(value).strip() + if text.isdigit(): + return int(text) * 1000 try: - retry_date = parsedate_to_datetime(retry_after_header) - delta = (retry_date - datetime.now(retry_date.tzinfo)).total_seconds() - return round(max(0, delta) * 1000) - except (ValueError, TypeError): - pass - - return None - - -def _get_sleep_interval( - exception: Exception, - initial_interval: int, - max_interval: int, - exponent: float, - retries: int, -) -> float: - """Get sleep interval for retry with exponential backoff. - - Args: - exception: The exception that triggered the retry. - initial_interval: Initial retry interval in milliseconds. - max_interval: Maximum retry interval in milliseconds. - exponent: Base for exponential backoff calculation. - retries: Current retry attempt count. - - Returns: - Sleep interval in seconds. + parsed = parsedate_to_datetime(text) + except (TypeError, ValueError): + return None + if parsed is None: + return None + now = datetime.now(parsed.tzinfo) if parsed.tzinfo is not None else datetime.utcnow() + delta_ms = int((parsed - now).total_seconds() * 1000) + return delta_ms if delta_ms > 0 else 0 + + +def execute_with_retries( + call_fn: Callable[[], Any], + retry_config: Optional[RetryConfig], + retry_status_codes: Optional[Iterable[Any]] = None, +) -> Any: + """Run call_fn() and retry on retryable failures per retry_config. + + `retry_config=None` means nothing was supplied, so fall back to the default backoff + policy (retry by default, matching Speakeasy). A RetryConfig with strategy "none" + disables retries -> just one attempt. `retry_status_codes` falls back to + DEFAULT_RETRY_STATUS_CODES. """ - if ( - isinstance(exception, TemporaryError) - and exception.retry_after is not None - and exception.retry_after > 0 - ): - return exception.retry_after / 1000 - - sleep = (initial_interval / 1000) * exponent**retries + random.uniform(0, 1) - return min(sleep, max_interval / 1000) - - -def retry(func, retries: Retries): - if retries.config.strategy == "backoff": - - def do_request() -> httpx.Response: - res: httpx.Response - try: - res = func() - - for code in retries.status_codes: - if "X" in code.upper(): - code_range = int(code[0]) - - status_major = res.status_code / 100 - - if code_range <= status_major < code_range + 1: - raise TemporaryError(res) - else: - parsed_code = int(code) - - if res.status_code == parsed_code: - raise TemporaryError(res) - except (httpx.NetworkError, httpx.TimeoutException) as exception: - if retries.config.retry_connection_errors: - raise - - raise PermanentError(exception) from exception - except TemporaryError: - raise - except Exception as exception: - raise PermanentError(exception) from exception - - return res - - return retry_with_backoff( - do_request, - retries.config.backoff.initial_interval, - retries.config.backoff.max_interval, - retries.config.backoff.exponent, - retries.config.backoff.max_elapsed_time, - ) - - return func() - - -async def retry_async(func, retries: Retries): - if retries.config.strategy == "backoff": - - async def do_request() -> httpx.Response: - res: httpx.Response - try: - res = await func() - - for code in retries.status_codes: - if "X" in code.upper(): - code_range = int(code[0]) - - status_major = res.status_code / 100 - - if code_range <= status_major < code_range + 1: - raise TemporaryError(res) - else: - parsed_code = int(code) - - if res.status_code == parsed_code: - raise TemporaryError(res) - except (httpx.NetworkError, httpx.TimeoutException) as exception: - if retries.config.retry_connection_errors: - raise - - raise PermanentError(exception) from exception - except TemporaryError: - raise - except Exception as exception: - raise PermanentError(exception) from exception - - return res - - return await retry_with_backoff_async( - do_request, - retries.config.backoff.initial_interval, - retries.config.backoff.max_interval, - retries.config.backoff.exponent, - retries.config.backoff.max_elapsed_time, - ) - - return await func() - - -def retry_with_backoff( - func, - initial_interval=500, - max_interval=60000, - exponent=1.5, - max_elapsed_time=3600000, -): - start = round(time.time() * 1000) - retries = 0 - + if retry_config is None: + retry_config = RetryConfig() + if getattr(retry_config, "strategy", "backoff") == "none": + return call_fn() + + codes = retry_status_codes if retry_status_codes is not None else DEFAULT_RETRY_STATUS_CODES + backoff = retry_config.backoff + elapsed_ms = 0 + attempt = 0 + last_exc: Optional[BaseException] = None while True: try: - return func() - except PermanentError as exception: - raise exception.inner - except Exception as exception: # pylint: disable=broad-exception-caught - now = round(time.time() * 1000) - if now - start > max_elapsed_time: - if isinstance(exception, TemporaryError): - return exception.response - - raise - - sleep = _get_sleep_interval( - exception, initial_interval, max_interval, exponent, retries + return call_fn() + except Exception as exc: + status = getattr(exc, "status", None) + if status is None: + status = getattr(exc, "status_code", None) + is_retryable_status = isinstance(status, int) and _matches_status(status, codes) + is_conn_err = retry_config.retry_connection_errors and ( + status == 0 or isinstance(exc, urllib3.exceptions.HTTPError) ) - time.sleep(sleep) - retries += 1 - - -async def retry_with_backoff_async( - func, - initial_interval=500, - max_interval=60000, - exponent=1.5, - max_elapsed_time=3600000, -): - start = round(time.time() * 1000) - retries = 0 - - while True: - try: - return await func() - except PermanentError as exception: - raise exception.inner - except Exception as exception: # pylint: disable=broad-exception-caught - now = round(time.time() * 1000) - if now - start > max_elapsed_time: - if isinstance(exception, TemporaryError): - return exception.response - + if not (is_retryable_status or is_conn_err): raise - - sleep = _get_sleep_interval( - exception, initial_interval, max_interval, exponent, retries + last_exc = exc + + # Decide sleep duration; abort if total elapsed exceeds budget + retry_after_ms = _retry_after_ms(last_exc) + if retry_after_ms is not None: + sleep_ms = min(retry_after_ms, backoff.max_interval) + else: + interval = min( + backoff.initial_interval * (backoff.exponent ** attempt), + backoff.max_interval, ) - await asyncio.sleep(sleep) - retries += 1 + # half-jitter + sleep_ms = int(interval / 2 + random.random() * (interval / 2)) + if elapsed_ms + sleep_ms > backoff.max_elapsed_time: + if last_exc is not None: + raise last_exc + return None + time.sleep(sleep_ms / 1000.0) + elapsed_ms += sleep_ms + attempt += 1 + + +__all__ = [ + "BackoffStrategy", + "RetryConfig", + "Retries", + "DEFAULT_RETRY_STATUS_CODES", + "execute_with_retries", +] diff --git a/platform/src/codat_platform/utils/security.py b/platform/src/codat_platform/utils/security.py deleted file mode 100644 index 42d8d78e9..000000000 --- a/platform/src/codat_platform/utils/security.py +++ /dev/null @@ -1,198 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -import base64 -from typing import ( - Any, - Dict, - List, - Optional, - Tuple, -) -from pydantic import BaseModel -from pydantic.fields import FieldInfo - -from .metadata import ( - SecurityMetadata, - find_field_metadata, -) - - -def get_security( - security: Any, allowed_fields: Optional[List[str]] = None -) -> Tuple[Dict[str, str], Dict[str, List[str]]]: - headers: Dict[str, str] = {} - query_params: Dict[str, List[str]] = {} - - if security is None: - return headers, query_params - - if not isinstance(security, BaseModel): - raise TypeError("security must be a pydantic model") - - sec_fields: Dict[str, FieldInfo] = security.__class__.model_fields - sec_field_names = ( - list(sec_fields.keys()) if allowed_fields is None else allowed_fields - ) - - for name in sec_field_names: - if name not in sec_fields: - continue - - sec_field = sec_fields[name] - - value = getattr(security, name) - if value is None: - continue - - metadata = find_field_metadata(sec_field, SecurityMetadata) - if metadata is None: - continue - if metadata.option: - _parse_security_option(headers, query_params, value) - return headers, query_params - if metadata.scheme: - # Special case for basic auth or custom auth which could be a flattened model - if metadata.sub_type in ["basic", "custom"] and not isinstance( - value, BaseModel - ): - _parse_security_scheme(headers, query_params, metadata, name, security) - else: - _parse_security_scheme(headers, query_params, metadata, name, value) - - if not metadata.composite: - return headers, query_params - - return headers, query_params - - -def _parse_security_option( - headers: Dict[str, str], query_params: Dict[str, List[str]], option: Any -): - if not isinstance(option, BaseModel): - raise TypeError("security option must be a pydantic model") - - opt_fields: Dict[str, FieldInfo] = option.__class__.model_fields - - for name in opt_fields: - opt_field = opt_fields[name] - - metadata = find_field_metadata(opt_field, SecurityMetadata) - if metadata is None or not metadata.scheme: - continue - - value = getattr(option, name) - if ( - metadata.scheme_type == "http" - and metadata.sub_type == "basic" - and not isinstance(value, BaseModel) - ): - _parse_basic_auth_scheme(headers, option) - return - - _parse_security_scheme(headers, query_params, metadata, name, value) - - -def _parse_security_scheme( - headers: Dict[str, str], - query_params: Dict[str, List[str]], - scheme_metadata: SecurityMetadata, - field_name: str, - scheme: Any, -): - scheme_type = scheme_metadata.scheme_type - sub_type = scheme_metadata.sub_type - - if isinstance(scheme, BaseModel): - if scheme_type == "http": - if sub_type == "basic": - _parse_basic_auth_scheme(headers, scheme) - return - if sub_type == "custom": - return - - scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields - for name in scheme_fields: - scheme_field = scheme_fields[name] - - metadata = find_field_metadata(scheme_field, SecurityMetadata) - if metadata is None or metadata.field_name is None: - continue - - value = getattr(scheme, name) - - _parse_security_scheme_value( - headers, query_params, scheme_metadata, metadata, name, value - ) - else: - _parse_security_scheme_value( - headers, query_params, scheme_metadata, scheme_metadata, field_name, scheme - ) - - -def _parse_security_scheme_value( - headers: Dict[str, str], - query_params: Dict[str, List[str]], - scheme_metadata: SecurityMetadata, - security_metadata: SecurityMetadata, - field_name: str, - value: Any, -): - scheme_type = scheme_metadata.scheme_type - sub_type = scheme_metadata.sub_type - - header_name = security_metadata.get_field_name(field_name) - - if scheme_type == "apiKey": - if sub_type == "header": - headers[header_name] = value - elif sub_type == "query": - query_params[header_name] = [value] - else: - raise ValueError("sub type {sub_type} not supported") - elif scheme_type == "openIdConnect": - headers[header_name] = _apply_bearer(value) - elif scheme_type == "oauth2": - if sub_type != "client_credentials": - headers[header_name] = _apply_bearer(value) - elif scheme_type == "http": - if sub_type == "bearer": - headers[header_name] = _apply_bearer(value) - elif sub_type == "basic": - headers[header_name] = value - elif sub_type == "custom": - return - else: - raise ValueError("sub type {sub_type} not supported") - else: - raise ValueError("scheme type {scheme_type} not supported") - - -def _apply_bearer(token: str) -> str: - return token.lower().startswith("bearer ") and token or f"Bearer {token}" - - -def _parse_basic_auth_scheme(headers: Dict[str, str], scheme: Any): - username = "" - password = "" - - if not isinstance(scheme, BaseModel): - raise TypeError("basic auth scheme must be a pydantic model") - - scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields - for name in scheme_fields: - scheme_field = scheme_fields[name] - - metadata = find_field_metadata(scheme_field, SecurityMetadata) - if metadata is None or metadata.field_name is None: - continue - - field_name = metadata.field_name - value = getattr(scheme, name) - - if field_name == "username": - username = value - if field_name == "password": - password = value - - data = f"{username}:{password}".encode() - headers["Authorization"] = f"Basic {base64.b64encode(data).decode()}" diff --git a/platform/src/codat_platform/utils/serializers.py b/platform/src/codat_platform/utils/serializers.py deleted file mode 100644 index d2149f8b9..000000000 --- a/platform/src/codat_platform/utils/serializers.py +++ /dev/null @@ -1,225 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from decimal import Decimal -import functools -import json -import typing -from typing import Any, Dict, List, Tuple, Union, get_args -import typing_extensions -from typing_extensions import get_origin - -import httpx -from pydantic import ConfigDict, create_model -from pydantic_core import from_json - -from ..types.basemodel import BaseModel, Nullable, OptionalNullable, Unset - - -def serialize_decimal(as_str: bool): - def serialize(d): - if d is None: - return None - if isinstance(d, Unset): - return d - - if not isinstance(d, Decimal): - raise ValueError("Expected Decimal object") - - return str(d) if as_str else float(d) - - return serialize - - -def validate_decimal(d): - if d is None: - return None - - if isinstance(d, (Decimal, Unset)): - return d - - if not isinstance(d, (str, int, float)): - raise ValueError("Expected string, int or float") - - return Decimal(str(d)) - - -def serialize_float(as_str: bool): - def serialize(f): - if f is None: - return None - if isinstance(f, Unset): - return f - - if not isinstance(f, float): - raise ValueError("Expected float") - - return str(f) if as_str else f - - return serialize - - -def validate_float(f): - if f is None: - return None - - if isinstance(f, (float, Unset)): - return f - - if not isinstance(f, str): - raise ValueError("Expected string") - - return float(f) - - -def serialize_int(as_str: bool): - def serialize(i): - if i is None: - return None - if isinstance(i, Unset): - return i - - if not isinstance(i, int): - raise ValueError("Expected int") - - return str(i) if as_str else i - - return serialize - - -def validate_int(b): - if b is None: - return None - - if isinstance(b, (int, Unset)): - return b - - if not isinstance(b, str): - raise ValueError("Expected string") - - return int(b) - - -def validate_const(v): - def validate(c): - if c is None: - return None - - if v != c: - raise ValueError(f"Expected {v}") - - return c - - return validate - - -def unmarshal_json(raw, typ: Any) -> Any: - return unmarshal(from_json(raw), typ) - - -def unmarshal(val, typ: Any) -> Any: - unmarshaller = create_model( - "Unmarshaller", - body=(typ, ...), - __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True), - ) - - m = unmarshaller(body=val) - - # pyright: ignore[reportAttributeAccessIssue] - return m.body # type: ignore - - -def marshal_json(val, typ): - if is_nullable(typ) and val is None: - return "null" - - marshaller = create_model( - "Marshaller", - body=(typ, ...), - __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True), - ) - - m = marshaller(body=val) - - d = m.model_dump(by_alias=True, mode="json", exclude_none=True) - - if len(d) == 0: - return "" - - return json.dumps(d[next(iter(d))], separators=(",", ":")) - - -def is_nullable(field): - origin = get_origin(field) - if origin is Nullable or origin is OptionalNullable: - return True - - if not origin is Union or type(None) not in get_args(field): - return False - - for arg in get_args(field): - if get_origin(arg) is Nullable or get_origin(arg) is OptionalNullable: - return True - - return False - - -def is_union(obj: object) -> bool: - """ - Returns True if the given object is a typing.Union or typing_extensions.Union. - """ - return any( - obj is typing_obj for typing_obj in _get_typing_objects_by_name_of("Union") - ) - - -def stream_to_text(stream: httpx.Response) -> str: - return "".join(stream.iter_text()) - - -async def stream_to_text_async(stream: httpx.Response) -> str: - return "".join([chunk async for chunk in stream.aiter_text()]) - - -def stream_to_bytes(stream: httpx.Response) -> bytes: - return stream.content - - -async def stream_to_bytes_async(stream: httpx.Response) -> bytes: - return await stream.aread() - - -def get_pydantic_model(data: Any, typ: Any) -> Any: - if not _contains_pydantic_model(data): - return unmarshal(data, typ) - - return data - - -def _contains_pydantic_model(data: Any) -> bool: - if isinstance(data, BaseModel): - return True - if isinstance(data, List): - return any(_contains_pydantic_model(item) for item in data) - if isinstance(data, Dict): - return any(_contains_pydantic_model(value) for value in data.values()) - - return False - - -@functools.cache -def _get_typing_objects_by_name_of(name: str) -> Tuple[Any, ...]: - """ - Get typing objects by name from typing and typing_extensions. - Reference: https://typing-extensions.readthedocs.io/en/latest/#runtime-use-of-types - """ - result = tuple( - getattr(module, name) - for module in (typing, typing_extensions) - if hasattr(module, name) - ) - if not result: - raise ValueError( - f"Neither typing nor typing_extensions has an object called {name!r}" - ) - return result diff --git a/platform/src/codat_platform/utils/unmarshal_json_response.py b/platform/src/codat_platform/utils/unmarshal_json_response.py deleted file mode 100644 index 4a526c509..000000000 --- a/platform/src/codat_platform/utils/unmarshal_json_response.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from typing import Any, Optional, Type, TypeVar, overload - -import httpx - -from .serializers import unmarshal_json -from codat_platform.models import errors - -T = TypeVar("T") - - -@overload -def unmarshal_json_response( - typ: Type[T], http_res: httpx.Response, body: Optional[str] = None -) -> T: ... - - -@overload -def unmarshal_json_response( - typ: Any, http_res: httpx.Response, body: Optional[str] = None -) -> Any: ... - - -def unmarshal_json_response( - typ: Any, http_res: httpx.Response, body: Optional[str] = None -) -> Any: - if body is None: - body = http_res.text - try: - return unmarshal_json(body, typ) - except Exception as e: - raise errors.ResponseValidationError( - "Response validation failed", - http_res, - e, - body, - ) from e diff --git a/platform/src/codat_platform/utils/url.py b/platform/src/codat_platform/utils/url.py deleted file mode 100644 index c78ccbae4..000000000 --- a/platform/src/codat_platform/utils/url.py +++ /dev/null @@ -1,155 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from decimal import Decimal -from typing import ( - Any, - Dict, - get_type_hints, - List, - Optional, - Union, - get_args, - get_origin, -) -from pydantic import BaseModel -from pydantic.fields import FieldInfo - -from .metadata import ( - PathParamMetadata, - find_field_metadata, -) -from .values import ( - _get_serialized_params, - _is_set, - _populate_from_globals, - _val_to_string, -) - - -def generate_url( - server_url: str, - path: str, - path_params: Any, - gbls: Optional[Any] = None, -) -> str: - path_param_values: Dict[str, str] = {} - - globals_already_populated = _populate_path_params( - path_params, gbls, path_param_values, [] - ) - if _is_set(gbls): - _populate_path_params(gbls, None, path_param_values, globals_already_populated) - - for key, value in path_param_values.items(): - path = path.replace("{" + key + "}", value, 1) - - return remove_suffix(server_url, "/") + path - - -def _populate_path_params( - path_params: Any, - gbls: Any, - path_param_values: Dict[str, str], - skip_fields: List[str], -) -> List[str]: - globals_already_populated: List[str] = [] - - if not isinstance(path_params, BaseModel): - return globals_already_populated - - path_param_fields: Dict[str, FieldInfo] = path_params.__class__.model_fields - path_param_field_types = get_type_hints(path_params.__class__) - for name in path_param_fields: - if name in skip_fields: - continue - - field = path_param_fields[name] - - param_metadata = find_field_metadata(field, PathParamMetadata) - if param_metadata is None: - continue - - param = getattr(path_params, name) if _is_set(path_params) else None - param, global_found = _populate_from_globals( - name, param, PathParamMetadata, gbls - ) - if global_found: - globals_already_populated.append(name) - - if not _is_set(param): - continue - - f_name = field.alias if field.alias is not None else name - serialization = param_metadata.serialization - if serialization is not None: - serialized_params = _get_serialized_params( - param_metadata, f_name, param, path_param_field_types[name] - ) - for key, value in serialized_params.items(): - path_param_values[key] = value - else: - pp_vals: List[str] = [] - if param_metadata.style == "simple": - if isinstance(param, List): - for pp_val in param: - if not _is_set(pp_val): - continue - pp_vals.append(_val_to_string(pp_val)) - path_param_values[f_name] = ",".join(pp_vals) - elif isinstance(param, Dict): - for pp_key in param: - if not _is_set(param[pp_key]): - continue - if param_metadata.explode: - pp_vals.append(f"{pp_key}={_val_to_string(param[pp_key])}") - else: - pp_vals.append(f"{pp_key},{_val_to_string(param[pp_key])}") - path_param_values[f_name] = ",".join(pp_vals) - elif not isinstance(param, (str, int, float, complex, bool, Decimal)): - param_fields: Dict[str, FieldInfo] = param.__class__.model_fields - for name in param_fields: - param_field = param_fields[name] - - param_value_metadata = find_field_metadata( - param_field, PathParamMetadata - ) - if param_value_metadata is None: - continue - - param_name = ( - param_field.alias if param_field.alias is not None else name - ) - - param_field_val = getattr(param, name) - if not _is_set(param_field_val): - continue - if param_metadata.explode: - pp_vals.append( - f"{param_name}={_val_to_string(param_field_val)}" - ) - else: - pp_vals.append( - f"{param_name},{_val_to_string(param_field_val)}" - ) - path_param_values[f_name] = ",".join(pp_vals) - elif _is_set(param): - path_param_values[f_name] = _val_to_string(param) - - return globals_already_populated - - -def is_optional(field): - return get_origin(field) is Union and type(None) in get_args(field) - - -def template_url(url_with_params: str, params: Dict[str, str]) -> str: - for key, value in params.items(): - url_with_params = url_with_params.replace("{" + key + "}", value) - - return url_with_params - - -def remove_suffix(input_string, suffix): - if suffix and input_string.endswith(suffix): - return input_string[: -len(suffix)] - return input_string diff --git a/platform/src/codat_platform/utils/values.py b/platform/src/codat_platform/utils/values.py deleted file mode 100644 index dae01a443..000000000 --- a/platform/src/codat_platform/utils/values.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from datetime import datetime -from enum import Enum -from email.message import Message -from functools import partial -import os -from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union, cast - -from httpx import Response -from pydantic import BaseModel -from pydantic.fields import FieldInfo - -from ..types.basemodel import Unset - -from .serializers import marshal_json - -from .metadata import ParamMetadata, find_field_metadata - - -def match_content_type(content_type: str, pattern: str) -> bool: - if pattern in (content_type, "*", "*/*"): - return True - - msg = Message() - msg["content-type"] = content_type - media_type = msg.get_content_type() - - if media_type == pattern: - return True - - parts = media_type.split("/") - if len(parts) == 2: - if pattern in (f"{parts[0]}/*", f"*/{parts[1]}"): - return True - - return False - - -def match_status_codes(status_codes: List[str], status_code: int) -> bool: - if "default" in status_codes: - return True - - for code in status_codes: - if code == str(status_code): - return True - - if code.endswith("XX") and code.startswith(str(status_code)[:1]): - return True - return False - - -T = TypeVar("T") - -def cast_partial(typ): - return partial(cast, typ) - -def get_global_from_env( - value: Optional[T], env_key: str, type_cast: Callable[[str], T] -) -> Optional[T]: - if value is not None: - return value - env_value = os.getenv(env_key) - if env_value is not None: - try: - return type_cast(env_value) - except ValueError: - pass - return None - - -def match_response( - response: Response, code: Union[str, List[str]], content_type: str -) -> bool: - codes = code if isinstance(code, list) else [code] - return match_status_codes(codes, response.status_code) and match_content_type( - response.headers.get("content-type", "application/octet-stream"), content_type - ) - - -def _populate_from_globals( - param_name: str, value: Any, param_metadata_type: type, gbls: Any -) -> Tuple[Any, bool]: - if gbls is None: - return value, False - - if not isinstance(gbls, BaseModel): - raise TypeError("globals must be a pydantic model") - - global_fields: Dict[str, FieldInfo] = gbls.__class__.model_fields - found = False - for name in global_fields: - field = global_fields[name] - if name is not param_name: - continue - - found = True - - if value is not None: - return value, True - - global_value = getattr(gbls, name) - - param_metadata = find_field_metadata(field, param_metadata_type) - if param_metadata is None: - return value, True - - return global_value, True - - return value, found - - -def _val_to_string(val) -> str: - if isinstance(val, bool): - return str(val).lower() - if isinstance(val, datetime): - return str(val.isoformat().replace("+00:00", "Z")) - if isinstance(val, Enum): - return str(val.value) - - return str(val) - - -def _get_serialized_params( - metadata: ParamMetadata, field_name: str, obj: Any, typ: type -) -> Dict[str, str]: - params: Dict[str, str] = {} - - serialization = metadata.serialization - if serialization == "json": - params[field_name] = marshal_json(obj, typ) - - return params - - -def _is_set(value: Any) -> bool: - return value is not None and not isinstance(value, Unset) diff --git a/platform/src/codat_platform/webhooks.py b/platform/src/codat_platform/webhooks.py index 2641d6baa..b90ac39a4 100644 --- a/platform/src/codat_platform/webhooks.py +++ b/platform/src/codat_platform/webhooks.py @@ -1,613 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_platform.webhooks — re-export of the webhooks method group.""" -from .basesdk import BaseSDK -from codat_platform import utils -from codat_platform._hooks import HookContext -from codat_platform.models import errors, operations, shared -from codat_platform.types import BaseModel, OptionalNullable, UNSET -from codat_platform.utils.unmarshal_json_response import unmarshal_json_response -from typing import Any, Mapping, Optional, Union, cast - - -class Webhooks(BaseSDK): - r"""Create and manage webhooks that listen to Codat's events.""" - - def create_consumer( - self, - *, - request: Optional[ - Union[ - shared.WebhookConsumerPrototype, - shared.WebhookConsumerPrototypeTypedDict, - ] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.WebhookConsumer: - r"""Create webhook consumer - - Use the *Create webhook consumer* endpoint to create a new webhook consumer that will listen to messages we send you. - - [Webhook consumer](https://docs.codat.io/platform-api#/schemas/WebhookConsumer) is an HTTP endpoint that you configure to subscribe to specific events. See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). - - ### Tips and traps - - The number of webhook consumers you can create is limited to 50. If you have reached the maximum number of consumers, use the [*Delete webhook consumer*](https://docs.codat.io/platform-api#/operations/delete-webhook-consumer) endpoint to delete an unused consumer first. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, Optional[shared.WebhookConsumerPrototype] - ) - request = cast(Optional[shared.WebhookConsumerPrototype], request) - - req = self._build_request( - method="POST", - path="/webhooks", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, False, True, "json", Optional[shared.WebhookConsumerPrototype] - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-webhook-consumer", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.WebhookConsumer, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def create_consumer_async( - self, - *, - request: Optional[ - Union[ - shared.WebhookConsumerPrototype, - shared.WebhookConsumerPrototypeTypedDict, - ] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.WebhookConsumer: - r"""Create webhook consumer - - Use the *Create webhook consumer* endpoint to create a new webhook consumer that will listen to messages we send you. - - [Webhook consumer](https://docs.codat.io/platform-api#/schemas/WebhookConsumer) is an HTTP endpoint that you configure to subscribe to specific events. See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). - - ### Tips and traps - - The number of webhook consumers you can create is limited to 50. If you have reached the maximum number of consumers, use the [*Delete webhook consumer*](https://docs.codat.io/platform-api#/operations/delete-webhook-consumer) endpoint to delete an unused consumer first. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, Optional[shared.WebhookConsumerPrototype] - ) - request = cast(Optional[shared.WebhookConsumerPrototype], request) - - req = self._build_request_async( - method="POST", - path="/webhooks", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, False, True, "json", Optional[shared.WebhookConsumerPrototype] - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-webhook-consumer", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.WebhookConsumer, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def delete_consumer( - self, - *, - request: Union[ - operations.DeleteWebhookConsumerRequest, - operations.DeleteWebhookConsumerRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Delete webhook consumer - - Use the *Delete webhook consumer* endpoint to delete an existing webhoook consumer, providing its valid `id` as a parameter. - - [Webhook consumer](https://docs.codat.io/platform-api#/schemas/WebhookConsumer) is an HTTP endpoint that you configure to subscribe to specific events. See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DeleteWebhookConsumerRequest) - request = cast(operations.DeleteWebhookConsumerRequest, request) - - req = self._build_request( - method="DELETE", - path="/webhooks/{webhookId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="delete-webhook-consumer", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def delete_consumer_async( - self, - *, - request: Union[ - operations.DeleteWebhookConsumerRequest, - operations.DeleteWebhookConsumerRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Delete webhook consumer - - Use the *Delete webhook consumer* endpoint to delete an existing webhoook consumer, providing its valid `id` as a parameter. - - [Webhook consumer](https://docs.codat.io/platform-api#/schemas/WebhookConsumer) is an HTTP endpoint that you configure to subscribe to specific events. See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DeleteWebhookConsumerRequest) - request = cast(operations.DeleteWebhookConsumerRequest, request) - - req = self._build_request_async( - method="DELETE", - path="/webhooks/{webhookId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="delete-webhook-consumer", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def list_consumers( - self, - *, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.WebhookConsumers: - r"""List webhook consumers - - Use the *List webhook consumers* endpoint to return a list of all webhook consumers that currently exist for your client. - - [Webhook consumer](https://docs.codat.io/platform-api#/schemas/WebhookConsumer) is an HTTP endpoint that you configure to subscribe to specific events. See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). - - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - req = self._build_request( - method="GET", - path="/webhooks", - base_url=base_url, - url_variables=url_variables, - request=None, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-webhook-consumers", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.WebhookConsumers, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def list_consumers_async( - self, - *, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.WebhookConsumers: - r"""List webhook consumers - - Use the *List webhook consumers* endpoint to return a list of all webhook consumers that currently exist for your client. - - [Webhook consumer](https://docs.codat.io/platform-api#/schemas/WebhookConsumer) is an HTTP endpoint that you configure to subscribe to specific events. See our documentation for more details on [Codat's webhook service](https://docs.codat.io/using-the-api/webhooks/overview). - - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - req = self._build_request_async( - method="GET", - path="/webhooks", - base_url=base_url, - url_variables=url_variables, - request=None, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-webhook-consumers", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.WebhookConsumers, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_platform.api.webhooks import Webhooks diff --git a/platform/src/codatplatform/_hooks/registration.py b/platform/src/codatplatform/_hooks/registration.py deleted file mode 100644 index 1db6a5293..000000000 --- a/platform/src/codatplatform/_hooks/registration.py +++ /dev/null @@ -1,13 +0,0 @@ -from .types import Hooks - - -# This file is only ever generated once on the first generation and then is free to be modified. -# Any hooks you wish to add should be registered in the init_hooks function. Feel free to define them -# in this file or in separate files in the hooks folder. - - -def init_hooks(hooks: Hooks): - # pylint: disable=unused-argument - """Add hooks by calling hooks.register{sdk_init/before_request/after_success/after_error}Hook - with an instance of a hook that implements that specific Hook interface - Hooks are registered per SDK instance, and are valid for the lifetime of the SDK instance"""